为什么即使我将整数转换为浮点数,对整数的计算也会被截断为整数?

时间:2019-04-18 13:11:53

标签: rust

即使函数的返回类型为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

1 个答案:

答案 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
    }
}

https://play.integer32.com/?version=stable&mode=debug&edition=2018&gist=7e71b3b0dc6491d5a39716a2b85a32d8