浮点异常 [英] Floating point exception
本文介绍了浮点异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#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不是素数,n);
else
{
int x;
for(x = 0; x if(n%x == 0)
{
printf(%d \ n is not素数,n);
return;
}
else
printf(%d \ n is prime,n);
$ b 但是当我运行我的代码我得到以下错误:
lockquote
浮点异常
$ /
这个错误意味着什么,我该如何解决它?
当$ x
为0时,你应该把x从2开始。一般说明:
- 尝试更好地设置您的代码的格式。专注于使用一致的风格。例如。你还有一个在if支撑(即使是空格)之后立即开始,另一个在两者之间有换行符。
- 除非必要,否则不要使用全局变量。没有理由将
q
设为全局。 在非void(int)函数中不返回值。
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?
解决方案 It's caused by n % x
, when x
is 0. You should have x start at 2 instead. You should not use floating point here at all, since you only need integer operations.
General notes:
- 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.
- Don't use globals unless necessary. There is no reason for
q
to be global.
- Don't return without a value in a non-void (int) function.
这篇关于浮点异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文