This function should print the averages of the odd and even inputs given from the while loop until 0 is entered, then it ends. It currently is not runnable, I split this block off from a larger section of code that had no correlation to the error. Any ideas where it would be giving the point exception error?
int main()
{
int numReturn;
int evenTotal;
int evenCount;
int oddTotal;
int oddCount;
while(numReturn != 0){
printf("Enter a positive integer: ");
scanf("%d",&numReturn);
if(numReturn<0){
printf("That's a negative number!\n");
}else if(numReturn%2 == 0){
evenTotal += numReturn;
evenCount += 1;
}else{
oddTotal += numReturn;
oddCount += 1;
}
}
double evenAvg = evenTotal/evenCount;
double oddAvg = oddTotal/oddCount;
printf("%d even numbers were entered and the average is %lf\n",evenCount,evenAvg);
printf("%d odd numbers were entered and the average is %lf\n",oddCount,oddAvg);
//some code for problem 1
return 0;
}
Variables with automatic storage duration (defined inside a function without
staticor other storage specifier) are not initialized by default. When such a variable is used, it does not have a determined value (and the program has undefined behavior if the variable could have been declared withregister, meaning its address is not taken).When the value of
evenCountoroddCountis taken as zero, a division by zero occurs inevenTotal/evenCountoroddTotal/oddCount. Likely, these are all integer variables, and this division by zero causes an exception. For historic reasons, this is reported as a “floating point exception.”To resolve this, you should first initialize the local variables:
Additionally:
evenCountoroddCountis zero because the user did not enter any even numbers or did not enter any odd numbers. In these cases, no average is defined.double evenAvg = evenTotal/evenCount;will computeevenTotal/evenCountusing integer arithmetic. Changing it todouble evenAvg = (double) evenTotal / evenCount;will usedoublearithmetic.