fnmain() { letmut a = String::new(); letmut b = String::new(); letmut c = String::new();
println!("Please input a"); std::io::stdin().read_line(&mut a).expect("Failed to read line"); leta: f64 = a.trim().parse().expect("Please type a number!"); println!("Please input b"); std::io::stdin().read_line(&mut b).expect("Failed to read line"); letb: f64 = b.trim().parse().expect("Please type a number!"); println!("Please input c"); std::io::stdin().read_line(&mut c).expect("Failed to read line"); letc: f64 = c.trim().parse().expect("Please type a number!"); nya(a, b, c); } fnnya(a: f64, b: f64, c: f64) { letdelta = (b * b) - (4.0 * a * c); if delta > 0.0 { letx1 = ((-b) + f64::sqrt(delta)) / (2.0 * a); letx2 = ((-b) - f64::sqrt(delta)) / (2.0 * a); println!("Two results: x1 = {}; x2 = {}.", x1, x2); } if delta == 0.0 { letx = (-b) / (2.0 * a); println!("One result: x = {}.", x); } if delta < 0.0 { println!("No result."); } }
细节
创建项目
1 2 3 4
$ cd ~/ $ mkdirtest $ cdtest $ cargo init
主函数部分
创建,然后没有返回值(
1 2 3
fnmain() {
}
声明 abc 变量
1 2 3 4 5
fnmain() { letmut a = String::new(); letmut b = String::new(); letmut c = String::new(); }
因为后续需要将String类型转换为浮点数,所以我们使用let mut确保系数是可变的变量。
然后获取输入呐~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
fnmain() { letmut a = String::new(); letmut b = String::new(); letmut c = String::new();
println!("Please input a"); std::io::stdin().read_line(&mut a).expect("Failed to read line"); leta: f64 = a.trim().parse().expect("Please type a number!"); println!("Please input b"); std::io::stdin().read_line(&mut b).expect("Failed to read line"); letb: f64 = b.trim().parse().expect("Please type a number!"); println!("Please input c"); std::io::stdin().read_line(&mut c).expect("Failed to read line"); letc: f64 = c.trim().parse().expect("Please type a number!"); }