这是我的代码。它是一个温度转换器,可以输入开尔文,摄氏度或华氏度,并输出相应的相反单位的转换值。
//问题:
//它将首先询问value,它必须是number,因此循环重新开始。这是可以的//然后它将要求单位,其必须是k、c或f。在不同的输入时,它确实捕获并打印“input k for kelvin,c for celcius F for Fahrenheit”//但是输入没有注册并跳转到循环的开始,要求数字的值。
//总而言之,我想用k,c或f来捕获单位变量,否则要求用户这样做,而不是跳到循环的开始。
//我正在学习生 rust ,所以请原谅我的任何不正常的事情。
//这里是我的main.rs:
fn main() {
println!("\nWelcome. This is Temperature-Converter\n");
println!("I work with Fahrenheit, Celsius and Kelvin");
println!("\nPlease Input the Value you want to convert: ");
loop{
let mut value = String::new();
std::io::stdin().read_line(&mut value).expect("Failed to read line");
let value:f32 = match value.trim().parse(){
Ok(num) => num,
Err(_) => {
println!("please input value in number(s).");
continue;
}
};
println!("Thank You, I have the value: {value}.\nPlease provide it's respective unit of measurement.");
println!("K : for Kelvin C : for Celsius F : for Fahrenheit : ");
let mut unit = String::new();
std::io::stdin().read_line(&mut unit).expect("Failed to read line");
let unit = unit.trim().to_uppercase();
let unit = match unit.as_str() {
"K"=>"K",
"F"=>"F",
"C"=>"C",
_=>{
println!("please input K, F or C for Kelvin, Fahrenheit or Celcius respectively.");
continue;
}
};
println!("Thank you for your input. I see that you want to convert {value} degree {unit}.");
println!("Please wait while i provide all possible conversions.\nThis will be quick.");
if unit == "K"{
let value_c = value-273.15;
let value_f = (((value-273.15)*9.0)+(32.0*5.0))/5.0;
println!("{value}{unit} is converted to: {value_c}C and {value_f}F");
println!("Thank You for using Temperature Conversior. It was a pleasure to assist you. Byee!!");
break;
}
else if unit == "C"{
let value_k = value+273.15;
let value_f = (value*(9.0/5.0))+32.0;
println!("{value}{unit} is converted to:{value_k}K and {value_f}F");
println!("Thank You for using Temperature Conversior. It was a pleasure to assist you. Byee!!");
break;
}
else if unit == "F"{
let value_k = (((value-32.0)*5.0)/9.0)+273.15;
let value_c = ((value-32.0)*5.0)/9.0;
println!("{value}{unit} is Converted to: {value_k}K and {value_c}C");
println!("Thank You for using Temperature-Converter. It was a pleasure to assist you. Byee!!");
break;
};
}
}
//我试过了:
if let unit = match unit.as_str() {
"K"=>"K",
"F"=>"F",
"C"=>"C",
_=>{println!("please input K, F or C for Kelvin, Fahrenheit or Celcius respectively.")}
};
//实际上我很难理解“match”和“loop”的作用域和返回值
2条答案
按热度按时间zlhcx6iw1#
程序逻辑仍然可以简化,现在这里只处理语法问题:
wqsoz72f2#
感谢用户:Kaplan我刚刚用循环定义了变量,后来用变量值打破循环出了循环。