# function call for a average function

Printable View

• 02-02-2002
ricekingg
function call for a average function
I'm having problems with the last function cal in main
"avg(amax, amin, 6, 80, 92, 77, 55, 99)". It returns garbage for the average value "a" and the variables that get passed by reference are incorect to. It's should find the average value of
6, 80, 92, 77, 55, 99 and max the value "99" and the min value
"6". Note the fuction defintion is at the end of the file.

#include<iostream.h>
#include<stdarg.h>

// functions prototyes(s)
int avg(int, ...);
double davg(int, ...);
int avg(int&, int&, int, ...);

void main()
{
cout << "The average of 6 integer test scores is " << avg(5, 81, 92, 73, 84, 95) << endl;
cout << "Press ENTER to continue..." << endl;
cin.get();

cout << "The average of 6 float test scores is "
<< davg(5.1, 81.0, 92.7, 73.4, 84.3, 95.6) << endl
<< "Press ENTER to continue..." << endl;
cin.get();

int a, amax, amin;
a = avg(amax, amin, 6, 80, 92, 77, 55, 99);
cout << "The average value is " << a << endl
<< "The maximum value is " << amax << endl
<< "the minimum value is " << amin << endl;
} // main

// returns average, and passes max and min back through argument list
int avg(int& mx, int& mn, int n, ...)
{
va_list list; // assign the name "list" to the variable length list of integers

va_start(list, n ); // tell C++ that the list to begines AFTER the "n"
int num; // store the numbers from the list in "num" as they are "read"

// create the toltal of "n" numers in the list
int toltal = 0; // truck the toltal of the numbers in the list
for ( int i = 0; i < n; i++)
{
num = va_arg(list, int); // set n equal to the next number inthe list, as an int
if ((i == 0) || (mn > num)) // update min value
mn = num;
if ((i == 0) || (mx < num)) //update max value
mx = num;
toltal = toltal + num; // incriment the toltal
}
va_end(list); // close the list

// compute and return the average
return toltal / n;
}
• 02-04-2002
swoopy
>// returns average, and passes max and min back through argument list
>int avg(int& mx, int& mn, int n, ...)

Based on the above function definition, the third parameter should be n, the number of integers to average. So this:
>a = avg(amax, amin, 6, 80, 92, 77, 55, 99);

Should either be:
a = avg(amax, amin, 5, 80, 92, 77, 55, 99);

Or if you want to average six integers:
a = avg(amax, amin, 6, 80, 92, 77, 55, 99, 200);