javascript - -nan 在 C++ 中是什么意思?为什么 pow(-4, -2.1) 返回 -nan?

标签 javascript c++ c++11

我明白为什么 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.

尝试使用在线工具编译它,但显示相同的结果:

最佳答案

我能找到的唯一相关引述来自 n1570 .

An implementation may give zero and values that are not floating-point numbers (such as infinities and NaNs) a sign or may leave them unsigned. Wherever such values are unsigned, any requirement in this International Standard to retrieve the sign shall produce an unspecified sign, and any requirement to set the sign shall be ignored.

关于javascript - -nan 在 C++ 中是什么意思?为什么 pow(-4, -2.1) 返回 -nan?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20452974/

相关文章:

javascript - 从下拉列表中选择值后 MVC 重新加载页面

c++ - 使用 STL 容器存储 Treeview 数据

c++ - 无法将迭代器设置为 std::map 的 std::pair

c++ - 尝试使用 find_if 函数通过第一个元素来查找成对 vector 中的值

c++ - 对数组 : can it actually happen? 的右值引用

c++ - FFMPEG中的av_opt_set是什么

javascript - 获取多个 DOM 元素的文本以便稍后在 D3.js 中重用

javascript - 主干.js : repopulate or recreate the view?

javascript - 在 JavaScript 中将负 float 转换为正 float

c++ - 正则表达式解析器