In: Computer Science
IN C++
Write a program to gauge the rate of inflation for the past year. The program asks for the price of an item (such as a hot dog or a one carat diamond) both one year ago and today. It estimates the inflation rate as the difference in price divided by the year ago price. Your program should allow the user to repeat this calculation as often as the user wishes. Define a function to compute the rate of inflation. The inflation rate should be a value of type double giving the rate as a percent, for example 5.3 for 5.3%.
Enter last year and this year's prices, please.
Enter prices as doubles
2
2.5
25.00%
Do you wish to do another? y
Enter last year and this year's prices, please.
Enter prices as doubles
5000
5200
4.00%
Do you wish to do another? n
C++ Code:
#include <iostream>
#include <iomanip>
using namespace std;
// function declaration
double calcaulteRateOfInflation(double lastYearPrice, double
currentYearPrice);
int main ()
{
// Variables declaration
char ch;
double lastYearPrice, currentYearPrice;
// Asking user input
cout << "Enter last year and this year's prices, please."
<< endl;
cout << "Enter prices as doubles" << endl;
cin >> lastYearPrice;
cin >> currentYearPrice;
// Calling function to compute the rate of inflation
double rateOfInflation = calcaulteRateOfInflation(lastYearPrice
,currentYearPrice);
// Displaying the rate of inflation in percentage with 2 decimal
values
std::cout << std::fixed;
std::cout << std::setprecision(2);
cout << rateOfInflation << "%" << endl;
// Allow the user to repeat this calculation
cout << "Do you wish to do another? ";
cin >> ch;
if(ch == 'y' || ch == 'Y'){
main(); // calling main method so it repeats this calculation
}
return 0;
}
// Define a function to compute the rate of inflation.
double calcaulteRateOfInflation(double lastYearPrice, double
currentYearPrice){
double rateOfInflation = currentYearPrice - lastYearPrice;
rateOfInflation = (rateOfInflation / lastYearPrice ) * 100;
return rateOfInflation;
}
Output:
Code Snapshots: