what are the cases when a floating point exception happens other than a divide by zero?

177 views Asked by At

i was writing some code to test the checksum for a credit card via an algorithm known as Luhn’s algorithm and verify if it's a valid card number or not the code i wrote is the program compiled fine but when i gave an input it said floating point exception i did some reading into when a floating point exception gets invoked but there was only one case which said that it occurs when you divide by zero but my program does not do that so i want to know what other cases can occur which lead to floating point exception.

#include <stdio.h>
int main(void)
{
     int a = get_int("enter your card number:");
    int x = 1  ;
    int z ;
    int y = 0 ;
    int s = 0  ;
    int d,k,m,g,h;
     int c ;
    int f = 1;
    int p = 0;
    bool checksum ;
    int l ;
    while ((a / (10^x) )> 1)
    {
        c = (a/10^x) ;
        z= c % 10 ;
        k = 2*z ;
        if  (k<10)
        {
            d = k;
        }
        else if (k>10||k==10)
        {
          d = (k%10) ;
        }
        y +=d;
        x+=2;
    }
    x=p;
    while ( (a / (10 ^ x) )>1 ) 
    {
        l= a/(10^x);
        m = l % 10 ;
        s += m;
        x+=2;
    }
     g= s+y;
     if(g%10==0)
     {
         checksum = 1 ;
        printf("valid");
     }
     else
     {
         checksum = 0 ; 
         printf("invalid");
     }
}```



1

There are 1 answers

0
Luis Colorado On

In my opinon, you think that 10 to the power of x is written in C as 10^x, but nothing farthest from that. 10^x is indeed 10 xor x (bitwise exclusive or) and not a to the power of operator. So if x happens to be 10, you get 0 as the denominator of the expresion and you will be, indeed, dividing by zero.

Anyway, It's my idea that you can have easier to handle your input if you accept indeed a string of digits, instead of an integer. As integer have limited precission, using an int will end you limiting your range of numbers from 0 to 4,204,967,295, while a credit card has between 15 and 20 digits, this can make inssuficient the range of numbers, to process a single card number.

On other side, if you analize your code, you will see that no floating point (neither division nor any other operation) is used in your program. This is because integer division produces the same exception as floating point division by zero. Both are signalled with the same exception, despite of the cause of the exception.