为什么我会收到“浮点异常:8" [英] Why am I getting 'Floating point exception: 8'

查看:54
本文介绍了为什么我会收到“浮点异常:8"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算 0 - 100 之间的所有质数,但出现浮点异常,谁能告诉我为什么?(如果有帮助,我正在使用 gcc)

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? (If it helps I'm using 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;
        }

此后,nums 的很多值都会是0.(可以打印查看)

After this, many values of nums will be 0.(You can print and check)

所以,当你在做的时候

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

将被0除,这会导致浮点异常

已编辑

事实上,只有在前两个for循环中才会出现浮点异常.当i=2j=2nums[2] 将更新为值 0.然后在 i=4j=2 的时候.会有除以0,因为num[2]已经是0,从而导致浮点异常

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. Then later when for i=4 and j=2. There will be a division by 0, because num[2] is already 0, thus causing the floating point exception

这篇关于为什么我会收到“浮点异常:8"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆