Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an average in C++?

Tags:

c++

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; 
like image 737
toby yeats Avatar asked Feb 17 '12 19:02

toby yeats


People also ask

How do you calculate sum and average in C?

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.


1 Answers

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(); 
like image 137
Charles Salvia Avatar answered Oct 09 '22 11:10

Charles Salvia