c++ - 面向初学者的 C++ 中的 nan

标签 c++ nan sqrt

#include <iostream>
#include <conio.h>
#include <math.h>

using namespace std;

int main ()
{
    float xstart = -2, xfinal = 2, h = 0.5;
    float t, y;

    cout << "X start = -2" << endl;
    cout << "X final = 2" << endl;
    cout << "step = 0.5" << endl << endl;

    for ( float x = xstart; x <= xfinal; x+= h)
    {
        t= sqrt(pow(sin(x),2)) / sqrt(x - 4);
        y= sqrt(2 * t + x);

        cout << x << " | " << t << " | " << y << endl;
    }

    cout << endl;
}

这会将 t 和 y 变量输出为 nan。我不知道如何修复它。该代码只是问题的示例,除了修复 nans 之外无需执行任何其他操作。

最佳答案

t= sqrt(pow(sin(x),2)) / sqrt(x - 4);

在 C++ 中,负数的平方根被定义为 NAN,“不是数字”。由于变量 x[-2, 2] 范围内迭代,你永远不会让它不是 NAN,这意味着使用它的所有计算都将到达南。

如果您希望 sqrt 返回复数,则需要使用 std::complex 及其各种数学函数。

关于c++ - 面向初学者的 C++ 中的 nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40537325/

相关文章:

javascript - 我不断收到 NaN,但我不知道如何解决它

javascript - 你如何在 JavaScript 中测试 NaN?

Java:性能 SQRT 计算

c - 对 sqrt(geany) 的 undefined reference

c++ - async_wait 中的 asio high_resolution_timer 段错误

c++ - 非命名空间范围内_内部结构_的显式特化

c++ - 将双向链表与 C++ 中的 Stack 和 Queue 类链接起来

c++ - Compute Shader 从多个线程组随机写入 RWStructuredBuffer

arrays - 将 numpy 数组中的 NaN 转换为大数(即 99999)

java - 了解 strictMath java 库