首页 > 解决方案 > 在 STDIN 之后编译然后在输入上进行数学运算时得到不匹配的类型

问题描述

我正在尝试编写一个 rust 程序来将输入温度从华氏温度转换为摄氏温度,反之亦然。我对 Rust 还是很陌生,并且提到了将这个程序作为一种学习方式的书。

当我尝试编译代码时,我不断收到错误不匹配的类型。错误可以立即在下面看到,并且我的代码在错误下方格式化。

错误[E0308]:类型不匹配
  --> 温度.rs:12:28
   |
12 | 让温度:u32 = temperature.trim().parse();
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^ 预期 u32,找到枚举`std::result::Result`
   |
   =注意:预期类型`u32`
              找到类型`std::result::Result`

错误[E0308]:类型不匹配
  --> 温度.rs:34:29
   |
34 | 让 fahr_result: f32 = ((温度 * 9) / 5) + 32;
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 预期 f32,找到 u32

错误[E0308]:类型不匹配
  --> 温度.rs:38:29
   |
38 | 让 celc_result: f32 = 温度 - 32 * 5 / 9;
   | ^^^^^^^^^^^^^^^^^^^^^^^^ 预期 f32,找到 u32
use std::io;

fn main () {
    println!("Welcome to the Temperature converter.");
    println!("Enter the temperature value, number only: ");

    let mut temperature = String::new();

    io::stdin().read_line(&mut temperature)
        .expect("Failed to read line");

    let temperature: u32 = temperature.trim().parse();

    println!("Do you want to convert to Celcius or Fahrenheit? (Enter the number of your choice)\n1. Fahrenheit\n2.Celcius");

    let mut temp_choice = String::new();

    io::stdin().read_line(&mut temp_choice)
        .expect("Failed to read line");

    let temp_choice: u32 = temp_choice.trim().parse()
        .expect("Fart in your butt.");

    if temp_choice == 1 {
        let fahr_result: f32 = ((temperature * 9) / 5) + 32;
        println!("{} degrees Celcius is equal to {} degrees Fahrenheit.", temperature, fahr_result);
    } else if temp_choice == 2 {
        let celc_result: f32 = temperature - 32 * 5 / 9;
        println!("{} degrees Fahrenheit is equal to {} degrees Celcius.", temperature, celc_result);
    } else {
        println!("Invalid Choice. Exiting.");
    }
}

标签: rust

解决方案


RustString.parse返回一个Result<F, <F as FromStr>::Err>,而不是一个字符串。最简单的做法是Result.unwrap像这样使用:

let temperature: u32 = temperature.trim().parse().unwrap();

注意如果parse返回错误结果,unwrap会panic,所以你可能要看看:

  • Result.unwrap_or它允许您在失败时提供默认值
  • Result.expect(正如您在其他地方使用的那样)Ok如果成功则返回结果的值,如果不成功则使用提供的文本参数恐慌

至于另一个问题,这是由于类型是整数 ( u32),所以数学也是整数(例如,5 / 9 = 0)。解决这个问题的一个简单方法是:

let fahr_result: f32 = (((temperature as f32) * 9.) / 5.) + 32.;

和:

let celc_result: f32 = (temperature as f32) - 32. * 5. / 9.;

作为奖励,由于运算顺序,摄氏度结果计算并不完全正确,因为乘法和除法将在减法之前执行。您可以通过将temperature - 32括号括起来来解决此问题,如下所示:

let celc_result: f32 = ((temperature as f32) - 32.) * 5. / 9.;

推荐阅读