简体   繁体   中英

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

    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.

在%操作之前打印num1的值,它得到0,然后除以0

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM