A simple math calculator I wrote using Rust as my programming language what does the program will do is to ask the user to give two numbers and then our program will compute for the sum, product, different and quotient of the given numbers. I hope you will find my work useful in learning rust programming.
Add me at Facebook my address is jakerpomperada@gmail.com and jakerpomperada@yahoo.com.
My mobile number here in the Philippines is 09173084360.
Sample Program Output
Program Listing
calc.rs
// Simple Calculator in Rust Programming language.
// Written By: Mr. Jake R. Pomperada, MAED-IT
// July 17, 2016
use std::io::{self, Write};
use std::fmt::Display;
use std::process;
fn main() {
println!("\n");
println!("\tSimple Calculator in Rust");
println!("\n");
let value1: i32 = grab_input("Enter First Number ")
.unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)))
.trim()
.parse()
.unwrap_or_else(|e| exit_err(&e, 2));
let value2: i32 = grab_input("Enter Second Number ")
.unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)))
.trim()
.parse()
.unwrap_or_else(|e| exit_err(&e, 2));
let sum = value1 + value2;
let subtract = value1 - value2;
let product = value1 * value2;
let quotient = value1 / value2;
println!("\n");
println!("===== DISPLAY RESULTS =====");
println!("\n");
println!("The sum of {} and {} is {}. ",value1,value2,sum);
println!("\n");
println!("The difference between {} and {} is {}. ",value1,value2,subtract);
println!("\n");
println!("The product of {} and {} is {}. ",value1,value2,product);
println!("\n");
println!("The quotient of {} and {} is {}. ",value1,value2,quotient);
println!("\n");
println!("End of Program");
}
fn grab_input(msg: &str) -> io::Result<String> {
let mut buf = String::new();
print!("{}: ", msg);
try!(io::stdout().flush());
try!(io::stdin().read_line(&mut buf));
Ok(buf)
}
fn exit_err<T: Display>(msg: T, code: i32) -> ! {
let _ = writeln!(&mut io::stderr(), "Error: {}", msg);
process::exit(code)
}
No comments:
Post a Comment