0.0/0.0 在 C++ 中产生负 nan 的任何原因?
Any reason why 0.0/0.0 makes negative nan in C++?
我从 SoloLearn 中找到了以下内容:
I found that 0.0/0.0 makes negative nan(-nan).
It makes sense to me that such a mathematical result is undefined, or "not a number". [...]
Furthermore, why is -nan+2^nan=nan?
例如:
#include <iostream>
using namespace std;
int main() {
cout<<0.0/0.0<<endl;
cout<<"important "+to_string(1.0/0.0)+"o:"<<endl;
cout<<"ba"+to_string(0.0/0.0*-1)+"a"<<endl;
cout<<(0.0/0.0)+2^(0.0/0.0*-1);//-nan+2^nan=nan
return 0;
}
但这不符合我的逻辑..
就C++语言而言,程序的行为是未定义的。因此,从 C++ 的角度来看,程序的行为没有任何“原因”。
根据 IEEE-754 浮点标准,假设您的硬件和语言实现符合它(他们可能符合),这种除法的结果是 NaN。 IEEE-754 没有为任何操作指定 NaN 的符号。因此,从 IEEE-754 的角度来看,答案是:由于语言/硬件实现选择的任何原因(或者只是没有特殊原因),它恰好在您的系统上如此。
总而言之:您永远不应该依赖 NaN 的符号是任何特定的东西。而且你通常应该避免被零除。
我从 SoloLearn 中找到了以下内容:
I found that 0.0/0.0 makes negative nan(-nan). It makes sense to me that such a mathematical result is undefined, or "not a number". [...]
Furthermore, why is -nan+2^nan=nan?
例如:
#include <iostream>
using namespace std;
int main() {
cout<<0.0/0.0<<endl;
cout<<"important "+to_string(1.0/0.0)+"o:"<<endl;
cout<<"ba"+to_string(0.0/0.0*-1)+"a"<<endl;
cout<<(0.0/0.0)+2^(0.0/0.0*-1);//-nan+2^nan=nan
return 0;
}
但这不符合我的逻辑..
就C++语言而言,程序的行为是未定义的。因此,从 C++ 的角度来看,程序的行为没有任何“原因”。
根据 IEEE-754 浮点标准,假设您的硬件和语言实现符合它(他们可能符合),这种除法的结果是 NaN。 IEEE-754 没有为任何操作指定 NaN 的符号。因此,从 IEEE-754 的角度来看,答案是:由于语言/硬件实现选择的任何原因(或者只是没有特殊原因),它恰好在您的系统上如此。
总而言之:您永远不应该依赖 NaN 的符号是任何特定的东西。而且你通常应该避免被零除。