【发布时间】:2013-12-08 21:12:58
【问题描述】:
我明白为什么 Math.pow(a, b) is NaN when a is a negative number and b is a non-integer 在 JavaScript 中。同样的事情正在发生in other programming languages。
但是,C++ 呢?
虽然在 JavaScript 中 Math.pow(-4, -2.1) 返回 NaN,但在 C++ 中 pow (-4, -2.1) 返回 -nan。为什么?
例子:
#include <iostream>
#include <math.h>
using namespace std;
int main () {
cout << "(4) ^ (2.1) = " << pow (4, -2.1) << endl; // 0.0544094
cout << "(-4) ^ (-2.1) = " << pow (-4, -2.1) << endl; // -nan
cout << "(-4) ^ (2.1) = " << pow (-4, 2.1) << endl; // -nan
return 0;
}
输出:
(4) ^ (2.1) = 0.0544094
(-4) ^ (-2.1) = -nan
(-4) ^ (2.1) = -nan
我使用g++编译了代码。
$ g++ --version
g++ (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
尝试使用在线工具编译它,但显示相同的结果:
【问题讨论】:
-
顺便说一句,您观察到的行为在 C++ 中不是必需的,它是一个实现细节。所需要的只是返回一个 NaN。一个实现有多少个 NaN,它们是什么,取决于具体的实现。
-nan是打印 NaN 的允许结果。您可能需要查看 glibc 中pow的来源,以确定它是否有意返回负 NaN 作为特例。
标签: javascript c++ c++11