Last active
August 28, 2025 15:59
-
-
Save yuhcee/4675920a247bf1583bbae46232dc4172 to your computer and use it in GitHub Desktop.
A simple Rust command-line calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::io; | |
| fn main() { | |
| println!("Simple Rust Calculator"); | |
| println!("--------------------"); | |
| loop { | |
| let mut input = String::new(); | |
| println!("Enter the first number:"); | |
| io::stdin().read_line(&mut input).expect("Failed to read line"); | |
| let first_number: f64 = match input.trim().parse() { | |
| Ok(num) => num, | |
| Err(_) => { | |
| println!("Invalid number. Please try again."); | |
| continue; | |
| } | |
| }; | |
| input.clear(); | |
| println!("Enter the operator (+, -, *, /):"); | |
| io::stdin().read_line(&mut input).expect("Failed to read line"); | |
| let operator: char = match input.trim().chars().next() { | |
| Some(op) => op, | |
| None => { | |
| println!("Invalid operator. Please try again."); | |
| continue; | |
| } | |
| }; | |
| input.clear(); | |
| println!("Enter the second number:"); | |
| io::stdin().read_line(&mut input).expect("Failed to read line"); | |
| let second_number: f64 = match input.trim().parse() { | |
| Ok(num) => num, | |
| Err(_) => { | |
| println!("Invalid number. Please try again."); | |
| continue; | |
| } | |
| }; | |
| let result = match operator { | |
| '+' => first_number + second_number, | |
| '-' => first_number - second_number, | |
| '*' => first_number * second_number, | |
| '/' => { | |
| if second_number == 0.0 { | |
| println!("Error: Division by zero!"); | |
| continue; | |
| } | |
| first_number / second_number | |
| } | |
| _ => { | |
| println!("Invalid operator. Please use +, -, *, or /."); | |
| continue; | |
| } | |
| }; | |
| println!("The result is: {}", result); | |
| input.clear(); | |
| println!("Do you want to perform another calculation? (y/n)"); | |
| io::stdin().read_line(&mut input).expect("Failed to read line"); | |
| if input.trim().to_lowercase() != "y" { | |
| break; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment