如何在Rust中组合if let和match表达式

huangapple go评论63阅读模式
英文:

How to combine if let match expression in rust

问题

Here is the translated code portion:

fn main() {
    println!("\n欢迎。这是温度转换器");
    println!("我可以处理华氏度、摄氏度和开尔文度");
    println!("\n请输入要转换的值:");

    loop {
        let mut value = String::new();
        std::io::stdin()
            .read_line(&mut value)
            .expect("读取输入失败");
        let value: f32 = match value.trim().parse() {
            Ok(num) => num,
            Err(_) => {
                println!("请输入数值。");
                continue;
            }
        };

        println!("谢谢,我已经获得了值:{}。", value);
        println!("请提供其相应的度量单位。");
        println!("K:开尔文    C:摄氏度    F:华氏度:");

        let mut unit = String::new();
        std::io::stdin()
            .read_line(&mut unit)
            .expect("读取输入失败");
        let unit = unit.trim().to_uppercase();
        let unit = match unit.as_str() {
            "K" => "K",
            "F" => "F",
            "C" => "C",
            _ => {
                println!("请输入K、F或C,分别表示开尔文、华氏度或摄氏度。");
                continue;
            }
        };

        println!("谢谢您的输入。我看到您要将 {} 度 {} 进行转换。", value, unit);
        println!("请稍候,我将提供所有可能的转换。\n这将很快完成。");

        if unit == "K" {
            let value_c = value - 273.15;
            let value_f = (((value - 273.15) * 9.0) + (32.0 * 5.0)) / 5.0;
            println!("{}{} 转换为:{}C 和 {}F", value, unit, value_c, value_f);
            println!("感谢您使用温度转换器。很高兴为您提供帮助。再见!");
            break;
        } else if unit == "C" {
            let value_k = value + 273.15;
            let value_f = (value * (9.0 / 5.0)) + 32.0;
            println!("{}{} 转换为:{}K 和 {}F", value, unit, value_k, value_f);
            println!("感谢您使用温度转换器。很高兴为您提供帮助。再见!");
            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!("{}{} 转换为:{}K 和 {}C", value, unit, value_k, value_c);
            println!("感谢您使用温度转换器。很高兴为您提供帮助。再见!");
            break;
        }
    }
}

Please note that I've replaced the HTML entities (") with regular double quotes (") for readability.

英文:

//here is my code. It is a Temperature Converter that takes input for Kelvin, Celsius or Fahrenheit and outputs converted value for corresponding contrary units.

// Problem:

// it will ask value first, which must be number, so the loop restarts. this is OK
// it will then ask for unit, which must be k,c or f. Upon different entry, it does catches and print "input k for kelvin, c for celcius F for Fahrenheit"
// But input doesnot register and jumps to the begening of the loop asking for value in numbers.

//All in all i want to catch the unit variable with k,c or f else ask the user to do so, not jump to the begening of loop.

// i am learning rust so excuse me for anything out of the norm.

//Here is my 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;
};
}
}

//i tried :

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.")}
};

// In fact i am having hard time understanding "match" and scope and return value of "loop"

答案1

得分: 0

程序逻辑仍可简化,目前只处理了语法问题:

    fn main() {
        println!("\n欢迎。这是温度转换器\n");
        println!("我可以处理华氏度、摄氏度和开尔文");
        println!("\n请输入您想转换的值:");

        loop {
            let mut input = String::new();
            let mut value = 0.0_f32;

            match std::io::stdin().read_line(&mut input) {
                Ok(_) => {
                    value = match input.trim().parse() {
                        Ok(num) => num,
                        Err(_) => {
                            println!("请以数字形式输入值。");
                            continue;
                        }
                    };
                    println!("谢谢,我已经得到值:{value}。");
                }
                Err(_) => println!("读取行失败"),
            }

            println!("请提供相应的计量单位。");
            println!("K:表示开尔文    C:表示摄氏度     F:表示华氏度:");

            let mut unit;
            loop {
                unit = String::new();
                match std::io::stdin().read_line(&mut unit) {
                    Ok(_) => {
                        unit = unit.trim().to_uppercase();
                        match unit.as_str() {
                            "K" | "F" | "C" => break,
                            _ => println!("请分别输入 K、F 或 C,表示开尔文、华氏度或摄氏度。"),
                        }
                    }
                    Err(_) => println!("读取行失败"),
                }
            }

            println!("感谢您的输入。我看到您想将 {value} 度 {unit} 进行转换。");
            println!("请稍候,我将提供所有可能的转换。\n这将很快完成。");

            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} 转换为:{value_c} 摄氏度和 {value_f} 华氏度");
                println!("感谢使用温度转换器。很高兴能帮助您。再见!");
                break;
            } else if unit == "C" {
                let value_k = value + 273.15;
                let value_f = (value * (9.0 / 5.0)) + 32.0;
                println!("{value}{unit} 转换为:{value_k} 开尔文和 {value_f} 华氏度");
                println!("感谢使用温度转换器。很高兴能帮助您。再见!");
                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} 转换为:{value_k} 开尔文和 {value_c} 摄氏度");
                println!("感谢使用温度转换器。很高兴能帮助您。再见!");
                break;
            };
        }
    }
英文:

The program logic can still be simplified, for now only the syntactical problems are dealt with here:

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 input = String::new();
let mut value = 0.0_f32;
match std::io::stdin().read_line(&mut input) {
Ok(_) => {
value = match input.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("please input value in number(s).");
continue;
}
};
println!("Thank You, I have the value: {value}.");
}
Err(_) => println!("Failed to read line"),
}
println!("Please provide it's respective unit of measurement.");
println!("K: for Kelvin    C: for Celsius     F: for Fahrenheit : ");
let mut unit;
loop {
unit = String::new();
match std::io::stdin().read_line(&mut unit) {
Ok(_) => {
unit = unit.trim().to_uppercase();
match unit.as_str() {
"K" | "F" | "C" => break,
_ => println!("please input K, F or C for Kelvin, Fahrenheit or Celcius respectively."),
}
}
Err(_) => println!("Failed to read line"),
}
}
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;
};
}
}

答案2

得分: 0

Sure, here is the translated code:

fn main() {
    
        println!("\n欢迎。这是温度转换器\n");
        println!("我可以处理华氏度,摄氏度和开尔文");
        println!("\n请输入您要转换的值:");
        
        let value: f32 = loop {
            let mut value = String::new();
            std::io::stdin()
                .read_line(&mut value)
                .expect("读取失败");
            match value.trim().parse::<f32>() {
                Ok(num) => break num,
                Err(_) => {
                    println!("请以数字输入值。");
                }
            };
        };
        println!("谢谢,我有这个值:{value}。\n请提供它的相应测量单位。");
        println!("K:开尔文    C:摄氏度     F:华氏度:");
        
        let unit = loop {
            let mut unit = String::new();
            std::io::stdin()
                .read_line(&mut unit)
                .expect("读取失败");
            let unit = unit.trim().to_uppercase();
            match &*unit {
                "K" | "F" | "C" => break unit,
                _ => {
                    println!("请分别输入K,F或C,表示开尔文,华氏度或摄氏度。\n我不区分大小写。");
                }
            };
        };

        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} 转换为:{value_c}摄氏度 和 {value_f}华氏度");
            println!("感谢您使用温度转换器。很高兴能帮助您。再见!!");
        }
        else if unit == "C" {
            let value_k = value + 273.15;
            let value_f = (value * (9.0 / 5.0)) + 32.0;
            println!("{value}{unit} 转换为:{value_k}开尔文 和 {value_f}华氏度");
            println!("感谢您使用温度转换器。很高兴能帮助您。再见!!");
        }
        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} 转换为:{value_k}开尔文 和 {value_c}摄氏度");
            println!("感谢您使用温度转换器。很高兴能帮助您。再见!!");
        };

}
英文:

Thanks for to user: Kaplan
i have just defined variables with loop and later break the loop with variable value out of the loop.

fn main() {
println!(&quot;\nWelcome. This is Temperature-Converter\n&quot;);
println!(&quot;I work with Fahrenheit, Celsius and Kelvin&quot;);
println!(&quot;\nPlease Input the Value you want to convert: &quot;);
let value:f32 = loop{
let mut value = String::new();
std::io::stdin()
.read_line(&amp;mut value)
.expect(&quot;Failed to read line&quot;);
match value.trim().parse::&lt;f32&gt;(){
Ok(num) =&gt; break num,
Err(_) =&gt; {
println!(&quot;please input value in number(s).&quot;);}
};
};
println!(&quot;Thank You, I have the value: {value}.\nPlease provide it&#39;s respective unit of measurement.&quot;);
println!(&quot;K : for Kelvin    C : for Celsius     F : for Fahrenheit : &quot;);
let unit = loop{
let mut unit = String::new();
std::io::stdin()
.read_line(&amp;mut unit)
.expect(&quot;Failed to read line&quot;);
let unit = unit.trim().to_uppercase();
match &amp;*unit{
&quot;K&quot; | &quot;F&quot; | &quot;C&quot; =&gt; break unit,
_=&gt;{
println!(&quot;Please input K, F or C for Kelvin, Fahrenheit or Celsius respectively.\nI am not case sensitive.&quot;);
}
};
};
if unit == &quot;K&quot;{
let value_c = value-273.15;
let value_f = (((value-273.15)*9.0)+(32.0*5.0))/5.0;
println!(&quot;{value}{unit} is converted to: {value_c}C and {value_f}F&quot;);
println!(&quot;Thank You for using Temperature Conversior. It was a pleasure to assist you. Byee!!&quot;);
}
else if unit == &quot;C&quot;{
let value_k = value+273.15;
let value_f = (value*(9.0/5.0))+32.0;
println!(&quot;{value}{unit} is converted to:{value_k}K and {value_f}F&quot;);
println!(&quot;Thank You for using Temperature Conversior. It was a pleasure to assist you. Byee!!&quot;);
}
else if unit == &quot;F&quot;{
let value_k = (((value-32.0)*5.0)/9.0)+273.15;
let value_c = ((value-32.0)*5.0)/9.0;
println!(&quot;{value}{unit} is Converted to: {value_k}K and {value_c}C&quot;);
println!(&quot;Thank You for using Temperature-Converter. It was a pleasure to assist you. Byee!!&quot;);
};
}

huangapple
  • 本文由 发表于 2023年5月18日 06:12:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76276513.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定