c - 浮点异常

标签 c floating-point

<分区>

我成功地遵守了这段代码:

#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);
        }
    }
}

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

Floating point exception

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

最佳答案

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

一般说明:

  1. 尝试更好地格式化您的代码。专注于使用一致的风格。例如。您还有一个在 if 大括号(甚至不是空格)之后立即开始的另一个,另一个在中间有一个换行符。
  2. 除非必要,否则不要使用全局变量。 q 没有理由是全局的。
  3. 不要在非 void (int) 函数中返回没有值。

关于c - 浮点异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3615476/

相关文章:

c++ - 如何找到样本信号在主信号中的位置?

c - 如何链接 librsync(可能使用了 libtool)

math - float 学有问题吗?

c++ - 如何准确打印 float 或 double 类型变量的小数点后 100 位?

c - c中串口读取,使用WinApi函数; WaitCommEvent 失败

c - 请解释这个结果。 printf ("%c", 'abcd' )

c - 按升序对数字重新排序(带前导零)

math - 如何为浮点选择epsilon值?

c++ - 为什么这个 float 比较会产生错误?

floating-point - 应该如何比较 OCaml 中的 float ?