Reputation: 1
I am passing an array of exam grades to the examAverage function along with the size of the array. When I printf the array contents in the for loop they are correct, but when they are added together the sum is wrong. Even if I printf immediately after I set double sum = 0, it says sum = 2. By the time the function is complete I get an extremely large number. Any help is appreciated.
double examAverage(int arr[], int size){
int i;
double exAvg=0;
double sum =0;
printf("Sum = %d\n", sum);
for (i = 0; i < size; ++i)
{
printf("Sum = %d\n", sum);
sum = arr[i];
}
exAvg = sum / size;
return exAvg;
}
Main
double examAverage(int arr[], int size);
printf("How many exam grades would you like to enter?\n");
scanf("%d", &examGrad);
int exams[examGrad];
printf("Enter exam grades \n");
for(int i=0; i<sizeof(exams)/sizeof(exams[0]); i++){
scanf("%d", &exams[i]);
}
double exAvg;
exAvg= examAverage(exams, examGrad);
printf("Exam average = %d", exAvg);
Output
How many exam grades to enter?
2
Enter exam grades
100
50
Sum = 2
Sum = 10
Sum = 1079574528
Exam Average = 1081159680
Upvotes: 0
Views: 85
Reputation: 1256
Don't You mean sum += arr[i];
in the for loop in examAverage
?
Also, Your code labeled Main is not really valid at all, first, there is no declaration of examGrad
, second the function declaration at the top does whoever knows what, third, sizeofs
in the for loop can be replaced by the examGrad, the %d
was already mentioned.
If You ask questions about simple code just include all of it, If it is too much, cut out the unnecessary parts or ensure us that they are there, otherwise we don't know if the problem is the missing code or not.
Upvotes: 2
Reputation: 17356
Do not use %d
to print a double
; that is for integers. Use %f
. The different way in which integers and floating point numbers are stored accounts for the problems that you are seeing.
You should have seen a warning about this when you compiled, along the lines of:
format specifies type 'int' but the argument has type 'double'
Upvotes: 1