Simple Math
Challenge
Read two numbers from stdin and compute their sum, difference, product, and quotient.
Solution
In previous challenges, we have learned how to read strings from stdin. Here we make a function for that:
fn read_line() -> Option<String> {
let mut input = String::new();
io::stdin().read_line(&mut input).ok()?;
Some(input.trim().to_string())
}
The next step is to convert input strings into integers. Luckily that can be done with the built-in
function str::parse().
let num1: i32 = read_line()
.expect("Cannot read line 1")
.parse()
.expect("Cannot parse the first line");
The second number can be parsed similarly.
The final step -- computing the two numbers' sum, difference, product, and quotients -- is straightforward with built-in operators:
println!("{} + {} = {}", num1, num2, num1 + num2);
println!("{} - {} = {}", num1, num2, num1 - num2);
println!("{} * {} = {}", num1, num2, num1 * num2);
println!("{} / {} = {}", num1, num2, num1 / num2);