+ 1
How do I calculate average in c++?
(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); }
1 Réponse
+ 1
Sum is uninitialized, which leads to compilation error and the value of average becoming unpredictable.
// Init sum
double sum = 0
Also, there's only 1 inflation rate, so dividing average by whatever value is unnecessary.
Declare a counter, for every time you get input from the user, increment counter. To compute average, divide it by counter.