Average function gone wrong.

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
/* **************************************************** */
//aver.h
/* **************************************************** */
#ifndef AVER_H_
#define AVER_H_
#endif
#include <cstdarg>

float aver(float count, ...)
{
va_list ap;
int j;
float tot;
va_start(ap, count);
for(j=0; j<count; j++)
        tot+=va_arg(ap, double);
va_end(ap);
return tot/count;
}
/* **************************************************** */
//Average.cpp
/* **************************************************** */
#include <aver.h>
#include <iostream>
using namespace std;

int main(){   
    double val = aver(4, 5, 6);
    cout << val << endl;
    cin.get();
    return 0;
}

When I try to average 4, 5, and 6, it gives me 1.#INF.
How can I get this to work right?
Last edited on
You've got to fix three things:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "aver.h"  // unless this is somewhere under ~/include use double quotes
#include <iostream>
using namespace std;

int main(){   
    double val = aver(
        3,          // aver() takes the number of additional args as first arg
        4., 5., 6.  // arguments must be floating point
        );
    cout << val << endl;
    cin.get();
    return 0;
}


One other thing... though I suspect you just did this for the example, aver() should only be prototyped in the .h file and it should be defined in a .cpp file.

Hope this helps.
Last edited on
Topic archived. No new replies allowed.