Floating point exception (core dumped) need help identifying where potential error is

68 views Asked by At

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;
}
1

There are 1 answers

0
Eric Postpischil On

Variables with automatic storage duration (defined inside a function without static or 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 with register, meaning its address is not taken).

When the value of evenCount or oddCount is taken as zero, a division by zero occurs in evenTotal/evenCount or oddTotal/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:

int numReturn = 0;
int evenTotal = 0;
int evenCount = 0;
int oddTotal  = 0;
int oddCount  = 0;

Additionally:

  • You should make provisions in the program for when evenCount or oddCount is zero because the user did not enter any even numbers or did not enter any odd numbers. In these cases, no average is defined.
  • When calculating the average, you should convert to floating-point before performing the division. double evenAvg = evenTotal/evenCount; will compute evenTotal/evenCount using integer arithmetic. Changing it to double evenAvg = (double) evenTotal / evenCount; will use double arithmetic.