Skip to content

Instantly share code, notes, and snippets.

@rajrkane
Created February 16, 2023 04:56
Show Gist options
  • Save rajrkane/8915bf9e46073c2e7e39a3ffcdee94c3 to your computer and use it in GitHub Desktop.
Save rajrkane/8915bf9e46073c2e7e39a3ffcdee94c3 to your computer and use it in GitHub Desktop.
Simple Temperature Converter in Rust
use std::io;
use std::io::Write;
fn main() {
println!("Welcome to the temperature converter!");
'program: loop {
println!("--------------------");
println!("Enter 1 for °F ➔ °C.");
println!("Enter 2 for °C ➔ °F.");
println!("Enter 3 to QUIT.");
'converter: loop {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line.");
let input: i32 = input.trim()
.parse()
.expect("Input not an integer.");
if input == 1 {
print!("°F: ");
io::stdout().flush().unwrap();
let mut fahr = String::new();
io::stdin()
.read_line(&mut fahr)
.expect("Failed to read line.");
let fahr: f32 = fahr.trim()
.parse()
.expect("Input not an integer.");
let cels: f32 = convert_to_cels(fahr);
println!("It is {cels} °C.");
break 'converter;
}
else if input == 2 {
print!("°C: ");
io::stdout().flush().unwrap();
let mut cels = String::new();
io::stdin()
.read_line(&mut cels)
.expect("Failed to read line.");
let cels: f32 = cels.trim()
.parse()
.expect("Input not an integer.");
let fahr: f32 = convert_to_fahr(cels);
println!("It is {fahr} °F.");
break 'converter;
}
else if input == 3 {
break 'program;
}
else {
println!("Options: 1, 2, 3.");
}
}
}
println!("Goodbye!");
}
fn convert_to_cels(fahr: f32) -> f32 {
(fahr - 32.0) * (5.0 / 9.0)
}
fn convert_to_fahr(cels: f32) -> f32 {
(cels * (9.0 / 5.0)) + 32.0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment