EduardoSaverin
EduardoSaverin

Reputation: 545

Why Floating Point Exception(Linux)

I am getting Floating Point Exception when i run this program on Linux.

#include<stdio.h>
#include<math.h>
int main()
{
    int num, num1, num2, n, i, j = 0, t, count = 0;
    int root;

    printf("Enter number of test cases\n");
    scanf("%d", &t);
    while (j < t)
    {
        scanf("%d", &num);
        root = (int)sqrt(num);
        for (i = 1; i < root; i++)
        {
            printf("Inside for");
            if (num % i == 0)
                num1 = i;
            while (num1 > 0)
            {
                n = num1 % 10;
                num1 = num1 / 10;
                if (n == 3 || n == 5 || n == 6)
                    count++;
            }
            if (num % num1 == 0)
            {
                num2 = (int)num / num1;
                while (num2 > 0)
                {
                    n = num2 % 10;
                    num2 = num2 / 10;
                    if (n == 3 || n == 5 || n == 6)
                        count++;
                }
            }
        }
        j++;
        count = 0;
        printf("%d", count);
    }
    return 0;
}

Can anyone please tell me how to correct it

Upvotes: 0

Views: 7570

Answers (3)

David Ranieri
David Ranieri

Reputation: 41055

Using a debugger:

Starting program: /home/david/demo 
Enter number of test cases
2
10

Program received signal SIGFPE, Arithmetic exception.
0x000000000040076d in main () at demo.c:26
26              if (num % num1 == 0)
(gdb) p num1
$1 = 0
(gdb) 

As you can see, the value of num1 is 0, division by 0

Upvotes: 0

eran
eran

Reputation: 6931

Print the value of num1 before % operation, it gets 0 and then you exception of division by 0

Upvotes: 0

keltar
keltar

Reputation: 18409

    while (num1 > 0)
    {
        n = num1 % 10;
        num1 = num1 / 10;
        if (n == 3 || n == 5 || n == 6)
            count++;
    }
    if (num % num1 == 0)

You rolling loop unless num1 becomes 0, then dividing by zero. Division by zero is guaranteed SIGFPE (at least on x86 and amd64). Despite name, it have nothing to do with floating point numbers.

Upvotes: 1

Related Questions