Converting temperature

The rust book had an assigment; converting between fahrenheit and celcius.

use std::io;

fn main() {
    loop {
        println!("Please enter 0 for fahrenheit to celcius, or 1 for celcius to fahrenheit.");
        let input_f32: f32 = read_input_line_f32();
        println!("");
        if input_f32 == 0.0 {
            println!("Converting from fahrenheit to celcius");
            println!("Please enter number of degrees fahrenheit that you want to convert to degrees celcius.");
            let mut fahrenheit_input: f32 = read_input_line_f32();
            let mut celcius: f32 = fahrenheit_to_celcius(fahrenheit_input);
            println!(
                "{} degrees fahrenheit is {} degrees celcius.",
                fahrenheit_input, celcius
            );
        } else {
            println!("Converting from celcius to fahrenheit.");
            println!("Please enter celcius degrees that you want to convert.");
            let mut celcius_input: f32 = read_input_line_f32();
            let mut fahrenheit: f32 = celcius_to_fahrenheit(celcius_input);
            println!(
                "{} degrees celcius is {} fahrenheit.",
                celcius_input, fahrenheit
            );
        }
        println!("");
    }
}

fn read_input_line_f32() -> f32 {
    loop {
        let mut input_string = String::new();
        println!("Enter number:");

        io::stdin()
            .read_line(&mut input_string)
            .expect("Failed to read line");

        let input_string: f32 = match input_string.trim().parse() {
            Ok(num) => return num,
            Err(_) => continue,
        };
    }
}

fn celcius_to_fahrenheit(celcius: f32) -> f32 {
    let fahrenheit = (celcius * 1.8) + 32.0;
    return fahrenheit;
}

fn fahrenheit_to_celcius(fahrenheit: f32) -> f32 {
    let celcius = (fahrenheit - 32.0) / 1.8;
    return celcius;
}

I guess this post is a code review request, though not explicitly mentioned. Am I right?

Normally we don't annotate every variable's types. You can basically remove all the : f32 tokens within function bodies from every functions here.

Below would be more idiomatic code with same behavior.

fn celcius_to_fahrenheit(celcius: f32) -> f32 {
    (celcius * 1.8) + 32.0
}
2 Likes

Tiny nitpick, and it doesn't matter for the correctness of the code, but Celsius isn't spelled with 2 c's.

1 Like

The muts in the main function are not needed because you don't modify the content of the variables.

1 Like

Thanks!

In general, inspect rustc warnings and suggestions and if you feel brave even run clippy. They have good suggestions.

1 Like