I have an assignment to read a file and output the average test scores.
It is pretty simple but I don't like how the average is done.
average = (test1 + test2 + test3 + test4 + test5) / 5.0;
Is there a way to just have it divide by the number of test scores? I couldn't find anything like this in the book or from google. Something like
average = (test + test + test + test) / ntests;
Step 1: Start Program. Step 2: Read the term of n numbers from the user. Step 3: Then read one by one numbers and calculate sum and average of n numbers using for loop or while loop. Step 4: Print sum and average n number.
If you have the values in a vector or an array, just use std::accumulate
from <numeric>
:
std::vector<double> vec; // ... fill vec with values (do not use 0; use 0.0) double average = std::accumulate(vec.begin(), vec.end(), 0.0) / vec.size();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With