Muhammad Ovais
Muhammad Ovais

Reputation: 152

Why is a calculation on integers truncated to an integer even though I've cast it to a float?

The below code is returning an integer instead of a float even though the return type of the function is a 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
}

I expect the output to be 98.6, instead it is just 98.

Upvotes: 3

Views: 152

Answers (1)

chpio
chpio

Reputation: 1064

You're doing the math on the integer type (which causes the unwanted rounding) and cast it afterwards to 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

Upvotes: 3

Related Questions