Search⌘ K
AI Features

Solution Review 2: Make a Calculator

Explore how to implement conditional logic in Rust by creating a calculator using if and match expressions. Understand controlling flow for operations like addition, subtraction, multiplication, division, and modulus, including handling division by zero and invalid inputs. Gain practical skills in managing complex conditional statements in Rust.

We'll cover the following...

Solution :

Rust 1.40.0
fn test(a: i32, operator: char ,b: i32) {
match operator {
'+' => {
println!("{}", a + b);
},
'-' => {
println!("{}", a - b);
},
'*' => {
println!("{}", a * b);
},
'/' => {
if b == 0{
println!("Division by 0 is undefined");
}
else {
println!("{}", a / b);
}
},
'%' => {
if b == 0{
println!("Mod 0 is undefined");
}
else {
println!("{}", a % b);
}
},
_ => println!("{}", "invalid operator"),
}
}
fn main(){
print!("3 + 2: ");
test(3,'+',2);
print!("3 - 2: ");
test(3,'-',2);
print!("3 * 2: ");
test(3,'*',2);
print!("3 / 2: ");
test(3,'/',2);
print!("3 % 2: ");
test(3,'%',2);
print!("3 ( 2: ");
test(3,'(',2);
print!("3 ( 0: ");
test(3, '/', 0)
}

Explanation

  • match ...