0

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

谁能告诉我如何纠正它

4

3 回答 3

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

您滚动循环,除非 num1 变为 0,然后除以零。SIGFPE 保证除以零(至少在 x86 和 amd64 上)。尽管有名称,但它与浮点数无关。

于 2013-10-15T11:05:00.443 回答
0

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

于 2013-10-15T11:05:24.800 回答
0

使用调试器:

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) 

可以看到,的值为num10,除以0

于 2013-10-15T11:06:52.777 回答