| 1 | use std::io; |
| 2 | |
| 3 | fn main() { |
| 4 | println!("Welcome to the Calculator!"); |
| 5 | |
| 6 | loop { |
| 7 | println!("Please enter an operator (+, -, *, /) or 'q' to quit:"); |
| 8 | let operator = read_input(); |
| 9 | |
| 10 | if operator == "q" { |
| 11 | break; |
| 12 | } |
| 13 | |
| 14 | println!("Please enter the first number:"); |
| 15 | let num1 = read_input().parse::<f64>().unwrap(); |
| 16 | |
| 17 | println!("Please enter the second number:"); |
| 18 | let num2 = read_input().parse::<f64>().unwrap(); |
| 19 | |
| 20 | let result = match operator.as_str() { |
| 21 | "+" => num1 + num2, |
| 22 | "-" => num1 - num2, |
| 23 | "*" => num1 * num2, |
| 24 | "/" => num1 / num2, |
| 25 | _ => { |
| 26 | println!("Invalid operator. Please try again."); |
| 27 | continue; |
| 28 | } |
| 29 | }; |
| 30 | |
| 31 | println!("Result: {}", result); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | fn read_input() -> String { |
| 36 | let mut input = String::new(); |
| 37 | io::stdin() |
| 38 | .read_line(&mut input) |
| 39 | .expect("Failed to read input"); |
| 40 | input.trim().to_string() |
| 41 | } |