5

这是 VB.NET 中的一个奇怪的计算错误。我已将我的问题简化为以下内容。我可以写:

Console.WriteLine(-0.78125 ^ 2.5)

并得到-0.53947966093944366.

但是,如果我将其更改为Console.WriteLine((-0.78125 + 0) ^ 2.5),我会得到-1.#IND

或者,如果它尝试:

Dim D as Double = -0.78125
Console.WriteLine(D ^ 2.5)

我也得到-1.#IND

如果我在表达式中使用单个文字数字,我只能得到返回结果的计算,但是当我使用任何数据类型的变量时,我得到-1.#IND.

我已经阅读了解释“-1.#IND”的其他帖子,但它们表明表达式中的一个数字是NaN,这里不是这种情况。为什么会这样?

4

1 回答 1

7

You can figure out what's going on by trying following:

Console.WriteLine(-1 ^ 0.5)

It prints -1, but in fact it is the same as sqrt(-1) which does not have a result in Real numbers. That's weird, isn't it? So what's going on here?

^ has higher precedence than -, so -1 ^ 0.5 is actually -(1 ^ 0.5). That's why it prints -1.

You can check the precedence list here: Operator Precedence in Visual Basic

The same happens with your code. -0.78125 ^ 2.5 is actually interpreted as -(0.78125 ^ 2.5) which is valid, but if you do (-0.78125 + 0) ^ 2.5 (or even (-0.78125) ^ 2.5) it's not valid anymore, because it would require calculating square root from negative value. That's why you're getting NaN (or -1#IND).

于 2013-09-08T20:43:51.023 回答