Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

accuracy lost

Status
Not open for further replies.

spiderling66

Programmer
Aug 21, 2004
5
0
0
GB
i am looking for the average of these double numbers, but i always got 5.0000, it's the accuracy lost, could anyone tell me what the problem is?

cheers

average (double a[], int n)
{
int i;
double av = 0.0;
for( i = 0; i < n; i++)
{
av += *a++;

}
return av;
}

main()
{
double a[] = {2.0, 3.5, 10.3};
double av = (average(a, 3))/3;
printf ("%lf\n", av);
}


 
Code:
#include<stdio.h>

double average (double a[], int n)
{
  int i;
  double av = 0.0;
  for( i = 0; i < n; i++)
  {
    av += *a++;
  }
  return av;
}

int main()
{
  double a[] = {2.0, 3.5, 10.3};
  double av = (average(a, 3))/3;
  printf ("%lf\n", av);
  return 0;
}

The above works fine and has been updated for modern compilers. You're using the old "K&R" style C and since you don't tell the compiler what type the function "average" returns, it doesn't know how to treat it, my guess is it makes it "int" by default. Changing it to "double average(double a[], int n)" made it work properly, giving 5.266667 instead of 5.0.
 
I think that's true of all compilers: functions return an int unless prototyped differently.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top