Function Crisis!

hey everyone im new to this site so forgive any wrong-doing. Heres my problem, in my class we have just started learning about functions, so for an assignment I had to rewrite a program by converting any formulas into functions and calling the functions in main. im having issues with my sum function. I complied it first to test like this:

double Add(double a) //function definition
{
static double c=0;

c=a+c;

return c;
}

it adds up 1-10 and works wonderfully in a while loop (while(!infile.eof()). the loop reads data from infile>>number; and it works fine.

the problem is when i use this to find the sum later on my numbers are bloated. here is the part of the code in my project:

tempmax=0;
tempmin=0;
count=0;
bigie=-100; //Because the high value will be above -100 for this area
smalie=1000; //Because the temperature on earth is always belowe 1000

infile>>tmax>>tmin;

while(!infile.eof())
{
loophilow(infile,tmax,tmin,bigie,smalie);
tempmax=sum(tmax); //call the sum function for max temp
tempmin=sum(tmin); //call the sum function for min temp
maxavg=avg(tempmax,count);
minavg=avg(tempmin,count);
count++;
infile>>tmax>>tmin;
}

AND THE FUNCTION;

double sum(double a)
{
static double c=0;

c=a+c;

return c;
}

so basically I call the function 'sum' in my loop but im not getting the right sums. my averages and everything else is working fine but not the sum!

any ideas?

thanks, devang
As 'c' is static, its value will continuously grow.
Pass it by reference instead:
1
2
3
4
5
double sum(double a, double &c)
{
   c=a+c; // you can write this c+=a
   return c;
}

 
sum(tmax,tempmax);

thanks for the quick response

i just had a DUH moment reading that

thanks again.

Topic archived. No new replies allowed.