我正在翻阅《铁 rust 手册》的第二版,并决定try 制作classic 的摄氏到华氏转换器:
fn c_to_f(c: f32) -> f32 {
return ( c * ( 9/5 ) ) + 32;
}
使用cargo build
编译此文件将产生编译时错误:
error[E0277]: the trait bound `f32: std::ops::Mul<{integer}>` is not satisfied
--> src/main.rs:2:12
|
2 | return (c * (9 / 5)) + 32;
| ^^^^^^^^^^^^^ the trait `std::ops::Mul<{integer}>` is not implemented for `f32`
|
= note: no implementation for `f32 * {integer}`
作为一名新的Rust程序员,我的解释是,我不能将浮点类型和整数类型相乘.我通过将所有常数设为浮点数来解决这个问题:
fn c_to_f(c: f32) -> f32 {
return ( c * ( 9.0/5.0 ) ) + 32.0;
}
这让我有所保留.来自C/C++/Java/Python,令人惊讶的是,您不能简单地对不同类型的数字执行算术运算.像我在这里做的那样,简单地将它们转换为相同的类型是正确的吗?