-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.rust
41 lines (35 loc) · 1.28 KB
/
calculator.rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
use std::io;
fn calculate(op: char, num1: f64, num2: f64) -> Option<f64> {
match op {
'+' => Some(num1 + num2),
'-' => Some(num1 - num2),
'*' => Some(num1 * num2),
'/' => {
if num2 != 0.0 {
Some(num1 / num2)
} else {
None
}
}
_ => None,
}
}
fn main() {
println!("Simple Calculator");
let mut input1 = String::new();
println!("Enter first number: ");
io::stdin().read_line(&mut input1).expect("Failed to read line");
let num1: f64 = input1.trim().parse().expect("Please enter a valid number");
let mut operation = String::new();
println!("Enter operation (+, -, *, /): ");
io::stdin().read_line(&mut operation).expect("Failed to read line");
let operation = operation.trim().chars().next().expect("Please enter a valid operation");
let mut input2 = String::new();
println!("Enter second number: ");
io::stdin().read_line(&mut input2).expect("Failed to read line");
let num2: f64 = input2.trim().parse().expect("Please enter a valid number");
match calculate(operation, num1, num2) {
Some(result) => println!("Result: {}", result),
None => println!("Error: Unsupported operation or division by zero."),
}
}