1#include <cstdarg>
2#include <iostream>
3
4using namespace std;
5
6// this function will take the number of values to average
7// followed by all of the numbers to average
8double average ( int num, ... )
9{
10 va_list arguments; // A place to store the list of arguments
11 double sum = 0;
12
13 va_start ( arguments, num ); // Initializing arguments to store all values after num
14 for ( int x = 0; x < num; x++ ) // Loop until all numbers are added
15 sum += va_arg ( arguments, double ); // Adds the next value in argument list to sum.
16 va_end ( arguments ); // Cleans up the list
17
18 return sum / num; // Returns the average
19}
20int main()
21{
22 // this computes the average of 13.2, 22.3 and 4.5 (3 indicates the number of values to average)
23 cout<< average ( 3, 12.2, 22.3, 4.5 ) <<endl;
24 // here it computes the average of the 5 values 3.3, 2.2, 1.1, 5.5 and 3.3
25 cout<< average ( 5, 3.3, 2.2, 1.1, 5.5, 3.3 ) <<endl;
26}
27