Friday, July 29, 2016

Product Cost Program in Rust

A program that I wrote using Rust programming language that will ask the user the cost of the product and its quantity after which it will compute its total cost. The code is very simple and intended for beginners in 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

// Product Cost Program in Rust Programming language.
// Written By: Mr. Jake R. Pomperada, MAED-IT
// July 28, 2016

use std::io::{self, Write};
use std::fmt::Display;
use std::process;


fn main() {
       println!("\n");
       println!("\tProduct Cost Program in Rust");
       println!("\n");

    let price: f32 = grab_input("Enter the price of the item ")
        .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 quantity: f32 = grab_input("Enter the quantity of the item  ")
        .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  solve_cost = price * quantity;
              
    println!("\n"); 
    println!("The total cost of the product is  $ {:.2}.",solve_cost);
    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