rust - 在 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.");
}
}
解决方案
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.;
推荐阅读
- c# - 使用 Angular 8 和 Azure Active Directory 进行身份验证
- jenkins - 为 Jenkinsfile 执行成功后的条件时出错
- amazon-web-services - 从 VPC 中的 ApiGateway 调用公共 ApiGateway
- jquery - 如何选择页面上的所有表,除非它们包含具有特定类的行
- amazon-cloudfront - CloudFront 重新加载后找不到 Nuxt.js 静态站点的页面
- python-3.x - 通过在 python3 中设置变量会发生“TypeError:字符串索引必须是整数”
- go - 无法为 INSERT 语句进行测试
- python - 为什么我修改 .copy() 时会覆盖原始列表?
- cube.js - 如何在 cube.js 中处理 postgres 数据库中的 jsonb 对象?
- css - 如果帖子在wordpress上有图片,如何隐藏特色图片