Reputation: 152
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
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
}
}
Upvotes: 3