+ 1
How do I add this part: Keep a running total of the valid inflation rates and the number of computed rates to calculate average
#include <iostream> using namespace std; double inflationRate (float old_cpi, float new_cpi); int main() { float old_cpi, new_cpi; char again; do { cout << "Enter the old and new consumer price indices: "; cin >> old_cpi >> new_cpi; cout << "Inflation rate is " << inflationRate(new_cpi, old_cpi) << endl; cout << "Try again? (y or Y): "; cin >> again; } while((again == 'Y') || (again == 'y')); return 0; } double inflationRate(float old_cpi, float new_cpi) { return ((old_cpi - new_cpi) / new_cpi * 100); }
3 Antworten
+ 4
You can use a vector of doubles to store your inflation rates.
Before asking for continuation, you can just push the last valid inflation rate inside the vector.
Then run a for loop like this:
double avg=0;
for(auto v:vec) avg+=v;
avg/=vec.size();
This will store the average of the vector named vec, inside avg.
Or you can just keep a variable avg, and add your inflation rate directly to it in the do...while loop. At the same time, keep incrementing a counter variable to keep note of the size, and in the end, divide avg by the counter variable to get the average.
+ 3
Here, try this : https://code.sololearn.com/c9BX9YiNRLxd/?ref=app
Your code has some errors, like you didn't define any variable named inflationRate. So you must call the function again when assigning to sum. And I think the average must be the sum divided by number of occurrences, which you must count using a counter variable for this case.
0
This is what I did so far: (average does not work)
#include <iostream>
using namespace std;
double inflationRate (float old_cpi, float new_cpi);
int main()
{
float old_cpi, new_cpi;
double sum, average;
cout << "Enter the old and new consumer price indices: ";
cin >> old_cpi >> new_cpi;
cout << "Inflation rate is " << inflationRate(old_cpi, new_cpi) << endl;
sum += inflationRate;
average = sum/inflationRtae;
cout << average << endl;
return 0;
}
double inflationRate(float old_cpi, float new_cpi)
{
return ((new_cpi - old_cpi) / old_cpi * 100);
}