这个问题已经有了答案:
C programming - floating point exception
5个答案
我成功地遵守了以下准则:
#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);
}
}
}
但是当我运行我的代码时,我会得到以下错误:
浮点异常
这个错误是什么意思?我怎样才能纠正它?
最佳答案
是由n % x
引起的,当x
为0时。你应该让x从2开始。这里根本不应该使用浮点,因为您只需要整数运算。
一般说明:
试着更好地格式化代码。专注于使用一致的风格。例如,有一个在if括号后立即开始(甚至没有空格),另一个括号中间有一个换行符。
除非有必要,否则不要使用globals。q
没有全球化的理由。
在非void(in t)函数中不返回值。