Convert Celsius to Farenheit in Rust
Hello, Today I decided to make a program that converts celsius to farenheit instead using Rust! If you want to see the python version. Here is how I do it.
- I create a input using a library
- create a function that calculates the formula of the conversion
- loop the question/input until they enter the correct input in this case you cannot type a
Stringorf64you only have to type in ai32or else it will give you a warning and loop.
Here is my code:
use std::io::{self, Write};
fn main() {
let temp = get_temp_in_celsius_input("Enter the temperature in Celsius: ");
println!("Temperature in Celsius: {}°C", temp);
println!("Temperature in Fahrenheit: {}°F", c_to_f(temp));
}
fn c_to_f(celsius: i32) -> f64 {
(celsius as f64) * 1.8 + 32.0
}
fn get_temp_in_celsius_input(prompt: &str) -> i32 {
loop {
// Print without a newline, so it stays in the buffer
print!("{}", prompt);
// Force the buffer to be written to the console
io::stdout().flush().expect("Failed to flush stdout");
let mut input = String::new();
io::stdin().read_line(&mut input).expect("FAILED TO READ LINE!");
let trimmed_input = input.trim(); // Remove leading/trailing whitespace and newline
match trimmed_input.parse::<i32>() {
Ok(good_input) => { return good_input; },
Err(error) => println!("error: {}", error)
}
}
}
Btw here is my code on Github.
Byeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :333333