为什么铸造NaN的一个长期收益有效的结果? [英] Why does casting a NaN to a long yield a valid result?

查看:105
本文介绍了为什么铸造NaN的一个长期收益有效的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码示例我零,当我通过它加强与调试器(股息/除数)产生一个无穷大或NaN(如果除数为零)分裂。当我投这个结果很长,我得到一个有效的结果,通常类似于-9223372036854775808。这是为什么投是否有效? ?为什么它不停止执行(抛出例如一个例外),而不是分配一个任意值

 双除数= 0; 
双重红利= 7;
长的结果=(长)(股息/除数);


解决方案

这是为什么投有效?




如果它是在编译时已知的转换是有效的,转换的可能的成功或总是的成功。石膏只有当违法转换不可能成功。从双(例如,铸造密封型,以它并没有实现一个接口)。A转换长可能会成功。因此,中投是有效的。




为什么它不停止执行(抛出例如一个例外),而不是分配一个任意值<? / p>


由于您没有要求例外!该规范是对预期的行为是极其明显。参见6.2.1节:




对于从float或double到整型的转换,处理取决于溢出检查中的上下文发生转换:



在选中的情况下,转换过程如下:



•如果值操作数是NaN或无穷大,则引发System.OverflowException。



[...]



在unchecked上下文中,转换总是会成功,并且进行如下:



•如果操作数的值是NaN或无穷大,转换的结果是不确定的。目标类型的值




您正在执行中unchecked上下文中的代码;你问也不例外所以你要也不例外。如果你想要一个例外,要求之一;使用checked上下文中。


In the sample code below I am dividing by zero which when I step through it with the debugger the (dividend / divisor) yields an Infinity or NaN (if the divisor is zero). When I cast this result to a long I get a valid result, usually something like -9223372036854775808. Why is this cast valid? Why doesn't it stop executing (throw an exception for example) rather than assign an arbitrary value?

double divisor = 0;
double dividend = 7;
long result = (long)(dividend / divisor);

解决方案

Why is this cast valid?

A cast is valid if it is known at compile time that the conversion might succeed or always succeeds. Casts are only illegal when the conversion cannot possibly succeed. (For example, casting a sealed type to an interface it does not implement.) A conversion from double to long might succeed. Therefore the cast is valid.

Why doesn't it stop executing (throw an exception for example) rather than assign an arbitrary value?

Because you didn't ask for an exception! The spec is extremely clear on what the expected behaviour is. See section 6.2.1:

For a conversion from float or double to an integral type, the processing depends on the overflow checking context in which the conversion takes place:

In a checked context, the conversion proceeds as follows:

• If the value of the operand is NaN or infinite, a System.OverflowException is thrown.

[...]

In an unchecked context, the conversion always succeeds, and proceeds as follows.

• If the value of the operand is NaN or infinite, the result of the conversion is an unspecified value of the destination type.

You're executing the code in an unchecked context; you asked for no exception so you're getting no exception. If you want an exception, ask for one; use a checked context.

这篇关于为什么铸造NaN的一个长期收益有效的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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