Last active
July 22, 2019 18:43
-
-
Save sanbox-irl/b4499cf187b96727b008dd75fa392295 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io; | |
fn main() { | |
println!("Type a temperature followed by \"C\" or \"F\" to convert."); | |
println!("Example:"); | |
println!("Input: 32F"); | |
println!("Output: 32F is 0C."); | |
'top: loop { | |
println!(); | |
println!("Type a temperature, please."); | |
let mut input = String::new(); | |
if let Err(msg) = io::stdin().read_line(&mut input) { | |
println!("Failed to read line {}", msg); | |
continue; | |
} | |
let input = input.trim(); | |
if input.len() == 0 { | |
println!("Please put in a valid temperature."); | |
return; | |
} | |
let mut parsed_number: i32 = 0; | |
let mut parsed_digit = 1; | |
let mut convert_to = ConvertTo::Celsius; | |
'inner: for (i, digit_char) in input.chars().rev().enumerate() { | |
if i == 0 { | |
if digit_char.is_alphabetic() == false { | |
println!("Please put in a valid temperature."); | |
return; | |
} | |
convert_to = ConvertTo::new(&digit_char) | |
.expect("Please input a valid temperature type, C or F."); | |
continue; | |
} | |
if i == input.len() - 1 && digit_char == '-' { | |
parsed_number *= -1; | |
break; | |
} | |
// Parse our digit and increase our Place | |
match parse_digit(parsed_digit, &digit_char) { | |
Ok(val) => { | |
parsed_number += val; | |
} | |
Err(msg) => { | |
println!( | |
"Digit \"{}\" was not a valid digit, 0-9. {}", | |
digit_char, msg | |
); | |
continue 'top; | |
} | |
}; | |
parsed_digit *= 10; | |
} | |
let last_num = convert_to.do_conversion(parsed_number); | |
println!( | |
"Input \"{}\" converted {:.1} Degrees {:?}", | |
input, last_num, convert_to | |
); | |
} | |
} | |
fn parse_digit(place: i32, this_char: &char) -> Result<i32, &'static str> { | |
match this_char.to_digit(10) { | |
Some(x) => Ok((x as i32) * place), | |
None => Err("It was not a digit!"), | |
} | |
} | |
#[derive(Debug)] | |
enum ConvertTo { | |
Celsius, | |
Fahrenheit, | |
} | |
impl ConvertTo { | |
pub fn new(temp_char: &char) -> Option<ConvertTo> { | |
match temp_char { | |
'C' => Option::Some(ConvertTo::Fahrenheit), | |
'F' => Option::Some(ConvertTo::Celsius), | |
_ => Option::None, | |
} | |
} | |
pub fn do_conversion(&self, value: i32) -> f64 { | |
match self { | |
ConvertTo::Celsius => self.fahrenheit_to_celsius(value), | |
ConvertTo::Fahrenheit => self.celsius_to_fahrenheit(value), | |
} | |
} | |
fn fahrenheit_to_celsius(&self, value: i32) -> f64 { | |
((value as f64) - 32.) * (5. / 9.) | |
} | |
fn celsius_to_fahrenheit(&self, value: i32) -> f64 { | |
(value as f64) * (9. / 5.) + 32. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment