mirror of
https://codeberg.org/unbeatable-101/FahrenheitToCelsius.git
synced 2024-06-17 22:37:07 +00:00
52 lines
1.6 KiB
Rust
52 lines
1.6 KiB
Rust
use std::io::stdin;
|
|
|
|
fn convert_to_c(temp: f32) -> f32 {
|
|
//subtracting 32 from the input
|
|
let mut celsius = temp - 32_f32;
|
|
//Defining what 5/9 is, then multiplying the input-32
|
|
const FIVE_DIV_NINE: f32 = 5.0 / 9.0;
|
|
celsius *= FIVE_DIV_NINE;
|
|
celsius
|
|
}
|
|
|
|
fn convert_to_f(temp: f32) -> f32 {
|
|
//Defining what 5/9 is, then deviding the input by it and adding 32
|
|
const FIVE_DIV_NINE: f32 = 5.0 / 9.0;
|
|
let mut fahrenheit = temp / FIVE_DIV_NINE;
|
|
fahrenheit += 32_f32;
|
|
fahrenheit
|
|
}
|
|
|
|
fn main() {
|
|
println!("Fahrenheit <--> Celsius converter");
|
|
println!("Press \"^C\" to end the program");
|
|
println!("Enter your number immidiatly followed by an F or C");
|
|
loop {
|
|
let mut input = String::new();
|
|
println!("Please input the temperature");
|
|
stdin()
|
|
.read_line(&mut input)
|
|
.expect("Failed to read line");
|
|
let input = input.trim();
|
|
/*
|
|
Split the input into two strings. Input, which contains the number;
|
|
and System, which contains if it is celcius or fahrenheit
|
|
*/
|
|
let (input,system) = input.split_at(input.len() - 1);
|
|
//If the input in a number, output it, else, restart loop
|
|
let input: f32 = match input.parse() {
|
|
Ok(num) => num,
|
|
Err(_) => continue,
|
|
};
|
|
/*
|
|
If the system is known, call the convert function,
|
|
otherwise repeat loop
|
|
*/
|
|
match system {
|
|
"C" => println!("{}°C is {:.2}°F", input, convert_to_f(input)),
|
|
"F" => println!("{}°F is {:.2}°C", input, convert_to_c(input)),
|
|
_ => continue,
|
|
};
|
|
}
|
|
}
|