Calculate simple interest and compound interest
Rust Programming Language
Problem
Rust program that calculates simple interest and compound interest.
Input
use std::io;fn main() {let principal = get_float_input("Enter the principal amount: ");let rate = get_float_input("Enter the interest rate: ");let time = get_float_input("Enter the time (in years): ");let simple_interest = calculate_simple_interest(principal, rate, time);let compound_interest = calculate_compound_interest(principal, rate, time);println!("Simple Interest: {:.2}", simple_interest);println!("Compound Interest: {:.2}", compound_interest);}fn get_float_input(prompt: &str) -> f64 {println!("{}", prompt);let mut input = String::new();io::stdin().read_line(&mut input).unwrap();input.trim().parse().unwrap()}fn calculate_simple_interest(principal: f64, rate: f64, time: f64) -> f64 {principal * rate * time / 100.0}fn calculate_compound_interest(principal: f64, rate: f64, time: f64) -> f64 {principal * (1.0 + rate / 100.0).powf(time) - principal}{codeBox}
Output
Here's an example output for an input of principal=1000, rate=5, and time=2.
Enter the principal amount:1000Enter the interest rate:5Enter the time (in years):2Simple Interest: 100.00Compound Interest: 105.10{codeBox}
Explanation
In this program, we use the io module to get user input for the principal, interest rate, and time period. We then calculate the simple interest and compound interest using the formulas.
Simple Interest = (P * R * T) / 100
Compound Interest = P * (1 + R / 100)^T - P
where P is the principal amount, R is the interest rate, and T is the time period (in years).
The get_float_input() function is a helper function that prompts the user for input and returns a f64 value.
The calculate_simple_interest() and calculate_compound_interest() functions take the P, R, and T values as arguments and return the corresponding interest values.
Finally, we print out the simple interest and compound interest values using println!() with format specifiers to format the output to two decimal places.