即使函数的返回类型为f32
,下面的代码也将返回整数而不是浮点数。
fn main() {
let temp = 37;
let degree = 'F';
let result = temp_conv(temp, degree);
println!("The equivalent of {}{} is: {}", temp, degree, result);
}
fn temp_conv(value: u32, degree: char) -> f32 {
let mut temperature: f32 = 0.0;
if degree == 'C' {
temperature = ((value - 32) * (5 / 9)) as f32;
} else if degree == 'F' {
temperature = ((value * 9 / 5) + 32) as f32;
} else {
temperature = 0.0;
};
temperature
}
我希望输出为98.6
,而只是98
。
答案 0 :(得分:3)
您正在对整数类型进行数学运算(这会导致不必要的舍入),然后将其强制转换为f32
。
fn main() {
let temp = 37;
let degree = 'F';
let result = temp_conv(temp, degree);
println!("The equivalent of {}{} is: {}", temp, degree, result);
}
fn temp_conv(value: u32, degree: char) -> f32 {
if degree == 'C' {
(value as f32 - 32.0) * (5.0 / 9.0)
} else if degree == 'F' {
(value as f32 * 9.0 / 5.0) + 32.0
} else {
0.0
}
}