除数为零 - c编程 [英] divide by zero - c programming

查看:406
本文介绍了除数为零 - c编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于下一个code问题:

I have a question about the next code:

int main { 
double x = 0;
double y = 0/x;

if(y==1) {.....}
....
....
return 0;
}

当我运行我的计算机上的code,我没有得到任何运行时错误,我看到 Y = -NAN(0x8000000000000)。为什么它不是一个运行时错误除以零?

When I run the code on my computer, I get no runtime error and I see that y = -nan(0x8000000000000). Why it is not a runtime error to divide by zero?

此外,当我改变了第一行 INT X = 0;
现在有一个运行时错误。有什么区别?

Additionally, when I change the first line to int x = 0; now there is a runtime error. What is the difference?

推荐答案

您不能依靠这种工作(即做同样的事情的时候,可移植)的话,那在C未定义行为第二的情况下,也为第一,如果您的实现并没有定义 __ __ STDC_IEC_559 (这是我认为,罕见的,这些天)。

You can't rely on this "working" (i.e. doing the same thing all the time, portably) at all, it's undefined behavior in C for the second case, and also for the first if your implementation doesn't define __STDC_IEC_559__ (this is, I believe, rare these days).

C99,§6.5.5/ 5

C99, §6.5.5/5

/操作的结果是从第一个操作数由相除所得的商
  第二; %操作的结果是余数。 在这两个运算中,如果价值
  第二个操作数是零,则行为是不确定的。

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

你要在一个案件一个不是一个数字和而不是在其他的事实是,一个是在浮点运算,做在哪里,您的实现(零语义符合IEEE 754师) , 0/0 给出了一个非数字。

The fact you're getting a "Not a Number" in one case and and not in the other is that one is done in floating-point arithmetic, where, on your implementation (conforming to IEEE 754 division by zero semantics), 0/0 gives a NaN.

在第二种情况下,你使用整数运算&ndash的;未定义的行为,有没有predicting会发生什么。

In the second case, you're using integer arithmetic – undefined behavior, there's no predicting what will happen.

这篇关于除数为零 - c编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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