题目来源:《The Rust Programming Language》第三章的课后小练习(一)
该书前三章从学习编程语言最经典的打印“Hello world!”开始入门,依次向我们介绍了rust语言环境的搭建,以及如何使用cargo
构建项目和编译、运行、rust
中的变量(可变性和不可变性)、数据类型、函数(带参、带返回值)、表达式和语句(比较细节的提到需读者自己留意)、元组(Tuple
)和数组、字符串、以及循环(loop
、for
、while
)等rust
入门知识。
题目:Convert temperatures between Fahrenheit and Celsius.
题目要求我们尝试使用以上学习的内容编写一个华式温度和摄氏温度的相互转换的小程序,下面将附上笔者在学习完前三章后完成该道题目的源码(如有错误欢迎指正,或者有改进指出也欢迎指出!!)
注:华式度=32+摄氏度x1.8; 摄氏度=(华式度 - 32)/1.8。(华式单位: °F, 摄氏单位: °C)
use std::io;
fn main() {
println!("Please select one to enter a number in Fahreheit and Celsius.");
println!("Please enter a key(Key F or f is Fahreheit, Key C or c is Celsius)");
let mut _fah: f64 = 0.0;
let mut _cel: f64 = 0.0;
let mut choose = String::new();
io::stdin()
.read_line(&mut choose)
.expect("Failed to read line.");
if (&choose[0..1] == "F") || (&choose[0..1] == "f") {
loop {
println!("Enter current Fahreheit:");
choose.clear();
io::stdin()
.read_line(&mut choose)
.expect("Failed to read line.");
_fah = match (&choose[0..choose.len() - 1])
.parse::<f64>() {
Ok(num) => num,
Err(_) => {
println!("It's not a number!");
continue;
},
};
_cel = (_fah - 32.0) / 1.8;
println!("Fahreheit: {} °F", _fah);
println!("Celsius: {} °C", _cel);
break;
}
} else if (&choose[0..1] == "C") || (&choose[0..1] == "c") {
loop {
println!("Enter current Celsius:");
choose.clear();
io::stdin()
.read_line(&mut choose)
.expect("Failed to read line.");
_cel = match (&choose[0..choose.len() - 1])
.parse::<f64>() {
Ok(num) => num,
Err(_) => {
println!("It's not a number!");
continue;
},
};
_fah = _cel * 1.8 + 32.0 ;
println!("Celsius: {} °C", _cel);
println!("Fahreheit: {} °F", _fah);
break;
}
} else {
println!("Invlid char.");
}
}