简体   繁体   English

为什么这个程序会出现浮点异常?

[英]Why there is floating point exception in this program?

#include <stdio.h>

int
main()
{
  int i;
  int c;
  int a[30] = { 5,  7,  11, 13,  17,  19,  23,  29,  31,  37,
                41, 43, 47, 53,  59,  61,  67,  71,  73,  79,
                83, 89, 97, 101, 103, 107, 109, 113, 127, 131 };
  for (i = 0; i < 30; i++) {
    c = (a[i] + i) / (i - 1);
    printf("Value of c is %d", c);
  }
}

I am not getting why I am facing floating point exception error in this program.我不明白为什么我在这个程序中面临浮点异常错误。

for(i = 0; i < 30; i++){
    c = (a[i] + i)/(i-1);

On the second iteration of this loop you divide by zero.在此循环的第二次迭代中,您除以零。

For historical reasons, on Unix systems integer division by zero is reported using the same signal (SIGFPE, "Floating point exception") that is used to report errors actually caused by floating-point arithmetic.由于历史原因,在 Unix 系统上,整数被零除是使用相同的信号(SIGFPE,“浮点异常”)报告的,该信号用于报告实际由浮点算术引起的错误。 This can't be changed now because too many existing programs depend on it.现在无法更改,因为太多现有程序依赖于它。

(I don't know what the historical reasons actually were. They're probably something along the lines of "the PDP-11 had a floating point divide instruction but not an integer divide instruction, so the original C compiler used floating point math to implement integer divide" but I just made that up, if it's true it's by accident.) (我不知道实际上是什么历史原因。它们可能类似于“PDP-11 有一个浮点除法指令而不是整数除法指令,所以原始的 C 编译器使用浮点数学来实现整数除法”,但我只是编造的,如果这是真的,那是偶然的。)

(Ironically, on a modern CPU floating-point division by zero will usually produce a ±Inf result but not trigger a signal, unless you use fesetenv to turn on trapping.) (具有讽刺意味的是,在现代 CPU 上,浮点除以零通常会产生 ±Inf 结果但不会触发信号,除非您使用fesetenv来打开捕获。)

In the second iteration of the loop, i is 1, so when you divide by i-1 , you are dividing by 0.在循环的第二次迭代中, i为 1,因此当您除以i-1 ,您除以 0。

How this would be fixed would depend on the purpose of your program.如何解决这个问题取决于你的程序的目的。

在第二次迭代i = 1因此你除以 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM