1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
#include <iostream>
using std::cout;
using std::endl;
#include <cstdarg>
// function prototype(s)
int avg(int, ...);
// return average of a variable length list of integers
int avg(int n, ...)// "n" is the number of numbers in the list; "..." is the list
{
va_list list; // assign the name "list" to the variable length list of integers
va_start(list, n); // tell C++ that the list begins AFTER the parameter "n"
int num; // store the numbers from the list in "num" as they are "read"
// create the total of "n" numbers in the list
int total = 0; // track the total of the numbers in the list
for (int i = 0; i < n; i++)
{
num = va_arg(list, int); // set num equal to the next number in the list, as an int
total = total + num; // increment the total
}
va_end(list); // close the list -- REQUIRED
// compute and return the average
return total / n;
}
double davg(int, ...);
double davg(int n, ...)
{
va_list list;
double sum2 = 0.0;
int total1 = 0;
va_start (list, n);
for (int x = 0; x < n; x++)
{ sum2 = va_arg(list, double);
total1 = total1 + sum2;
}
va_end(list);
total1 = total1 / n;
return total1;
}
int main()
{
cout << "The average of 5 test scores is " << avg(5, 81, 92, 73, 84, 95) << endl;
cout << "The average of 5 test scores is " << davg(56.8, 87.9, 99.2, 76.5, 85.3) << endl;
}
|