P
Peter
I have written this small app to explain an issue I'm having with a larger
program.
In the following code I'm taking 10 ints from the keyboard. In the call to
average() these 10 ints are then added and Divided by the number of ints to
return the average, a float.
Can someone see why I get for example: if the total is 227 then divided by
10 I get a return of 22.00000 instead of the correct answer 22.7.
Thanks in advance
Pete
#include <stdio.h>
float average(int, int[]); /* Prototype returning float */
int main()
{
int num[10]; /* array to hold 10 ints */
float avg; /* float to hold the average */
int i, size=10;
printf("Enter 10 integers: \n");
/* Takes ten ints for keyboard */
for(i=0; i<size; i++)
{
scanf("%d", &num);
}
avg = average(size, num); /* Call to average() passing size and array */
printf("%f", avg);
}
/* average() calculates total of 10 ints & calculates average, returns float
ans */
float average(int count, int numbers[])
{
int total=0;
int i;
float ans;
for(i=0; i<count; i++)
{
total +=numbers;
/*printf("Total = %d \n", total);*/
ans = total/count;
}
return ans;
}
program.
In the following code I'm taking 10 ints from the keyboard. In the call to
average() these 10 ints are then added and Divided by the number of ints to
return the average, a float.
Can someone see why I get for example: if the total is 227 then divided by
10 I get a return of 22.00000 instead of the correct answer 22.7.
Thanks in advance
Pete
#include <stdio.h>
float average(int, int[]); /* Prototype returning float */
int main()
{
int num[10]; /* array to hold 10 ints */
float avg; /* float to hold the average */
int i, size=10;
printf("Enter 10 integers: \n");
/* Takes ten ints for keyboard */
for(i=0; i<size; i++)
{
scanf("%d", &num);
}
avg = average(size, num); /* Call to average() passing size and array */
printf("%f", avg);
}
/* average() calculates total of 10 ints & calculates average, returns float
ans */
float average(int count, int numbers[])
{
int total=0;
int i;
float ans;
for(i=0; i<count; i++)
{
total +=numbers;
/*printf("Total = %d \n", total);*/
ans = total/count;
}
return ans;
}