[英]Why am I getting 'Floating point exception: 8'
I'm trying to calculate all the prime numbers from 0 - 100 and I'm getting a floating point exception, could anyone tell me why? 我正在尝试计算0到100之间的所有素数,并且遇到了浮点异常,有人可以告诉我为什么吗? (If it helps I'm using gcc)
(如果有帮助,我正在使用gcc)
#include <stdio.h>
int main(void)
{
int nums[100], i;
for(i=0;i<100;i++)
nums[i] = i;
int j,k,l,z;
for(i=1;i<100;i++)
for(j=2;j<100;j++)
if((nums[i] % nums[j]) == 0)
{
nums[j] = 0;
}
for(i=0;i<100;i++)
if(nums[i] != 0)
break;
for(z=0;z<100;z++)
{
for(k=i;k<100;k++)
for(l = (k+2);l < 100;l++)
if((nums[k] % nums[l]) == 0)
nums[k] = 0;
}
for(i=0;i<100;i++)
if(nums[i] != 0)
printf("%d,",nums[i]);
printf("\n");
return 0;
}
Well, it's really hard to understand what your code is doing. 好吧,很难理解您的代码在做什么。 But still
但是还是
for(i=1;i<100;i++)
for(j=2;j<100;j++)
if((nums[i] % nums[j]) == 0)
{
nums[j] = 0;
}
After this, many values of nums
will be 0
.(You can print and check) 之后,许多
nums
值将为0
(您可以打印并检查)
So, Later when you are doing 所以,以后做的时候
for(z=0;z<100;z++)
{
for(k=i;k<100;k++)
for(l = (k+2);l < 100;l++)
if((nums[k] % nums[l]) == 0) //Part where division by 0 occurs
nums[k] = 0;
}
There will be a division by 0
, which is giving the floating point exception
将除以
0
,得到floating point exception
Edited 编辑
Infact, there will be a floating point exception
in the first two for
loops only.. When i=2
and j=2
, nums[2]
will get updated to value 0
. 实际上,仅在前两个
for
循环中会有一个floating point exception
。.当i=2
和j=2
, nums[2]
将更新为值0
。 Then later when for i=4
and j=2
. 然后,当
i=4
且j=2
。 There will be a division by 0
, because num[2]
is already 0
, thus causing the floating point exception
将被
division by 0
,因为num[2]
已经为0
,从而导致floating point exception
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.