C语言 浮点异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3615476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:21:15  来源:igfitidea点击:

Floating point exception

cfloating-point

提问by Shelith

I successfully complied this code:

我成功地编译了这段代码:

#include <stdio.h>
#include <math.h>
int q;

int main()
{
    srand( time(NULL) );
    int n=3;
    q=ceil(sqrt(n));
    printf("%d\n %d\n", n,q);

    if(n == 2)
        printf("%d\n is prime", n);
    else if(n % 2 == 0.0 || n < 2)
        printf("%d\n is not prime", n);
    else
    {
        int x;
        for(x = 0; x < q; x++){
            if(n % x == 0)
            {
                printf("%d\n is not prime", n);
                return;
            }
            else
                printf("%d\n is prime", n);
        }
    }
}

But when I run my code I get the following error:

但是当我运行我的代码时,我收到以下错误:

Floating point exception

浮点异常

What does this error mean and how can I fix it?

这个错误是什么意思,我该如何解决?

回答by Matthew Flaschen

It's caused by n % x, when xis 0. You should have x start at 2 instead. You should not use floating point here at all, since you only need integer operations.

它是由n % x, whenx为 0引起的。您应该让 x 从 2 开始。您根本不应该在这里使用浮点数,因为您只需要整数运算。

General notes:

一般注意事项:

  1. Try to format your code better. Focus on using a consistent style. E.g. you have one else that starts immediately after a if brace (not even a space), and another with a newline in between.
  2. Don't use globals unless necessary. There is no reason for qto be global.
  3. Don't return without a value in a non-void (int) function.
  1. 尝试更好地格式化您的代码。专注于使用一致的风格。例如,您有一个紧跟在 if 大括号(甚至不是空格)之后开始的其他数据,以及另一个中间有换行符的数据。
  2. 除非必要,否则不要使用全局变量。没有理由q成为全球性的。
  3. 不要在非 void (int) 函数中没有值就返回。

回答by realkstrawn93

http://en.wikipedia.org/wiki/Division_by_zero

http://en.wikipedia.org/wiki/Division_by_zero

http://en.wikipedia.org/wiki/Unix_signal#SIGFPE

http://en.wikipedia.org/wiki/Unix_signal#SIGFPE

This should give you a really good idea. Since a modulus is, in its basic sense, division with a remainder, something % 0IS division by zero and as such, will trigger a SIGFPE being thrown.

这应该给你一个非常好的主意。由于模数在其基本意义上是除以余数,因此something % 0被零除,因此将触发 SIGFPE 被抛出。

回答by Andre Holzner

It's caused by n % xwhere x = 0in the first loop iteration. You can't calculate a modulus with respect to 0.

它是由引起的n % x,其中x = 0在第一循环迭代。您无法计算相对于 0 的模数。