算法小白的心得笔记:关于Nan

NaN 是什么

在C++中,NaN(Not a Number)是一种特殊的浮点数值,用于表示无法表示的数值或未定义的操作,例如0除以0。如果你的double类型变量显示为NaN,那么可能是在计算过程中出现了这种未定义的操作。

如果你想检查一个double类型变量是否为NaN,你可以使用C++标准库中的std::isnan函数。例如:

#include <cmath> // for std::isnan

double d = std::sqrt(-1); // this will be NaN

if (std::isnan(d)) {
    std::cout << "d is NaN" << std::endl;
} else {
    std::cout << "d is not NaN" << std::endl;
}

在上述代码中,std::sqrt(-1)会返回NaN,因为不能对负数开平方。然后我们使用std::isnan来检查d是否为NaN。

如果你想打印一个double类型的NaN值,你可以直接使用std::cout,例如:

double d = std::sqrt(-1); // this will be NaN
std::cout << d << std::endl; // this will print "nan"

这将打印出"nan"。

怎么存放一个NaN类型的值

在C++中,你可以使用标准库中的函数std::nan("")来创建一个NaN值,并将其存放在一个double类型的变量中。例如:

#include <cmath> // for std::nan

double d = std::nan("");

std::cout << d << std::endl; // this will print "nan"

在上述代码中,std::nan("")会返回一个NaN值,我们将其存放在double类型的变量d中。然后我们打印d,将会输出"nan"。

另外,你也可以通过一些未定义的数学操作来得到NaN值,例如0除以0,或者对负数开平方等。例如:

double d = 0.0 / 0.0; // this will be NaN

std::cout << d << std::endl; // this will print "nan"

在上述代码中,0除以0是未定义的,所以结果是NaN。我们将这个结果存放在double类型的变量d中,然后打印d,将会输出"nan"。

std::nan(“”)需要什么头文件

std::nan("")函数需要包含<cmath>头文件。这个函数是C++标准库中的数学函数,用于生成一个"非数字"(NaN)的特殊浮点值。

所以,你的代码应该是这样的:

#include <cmath> // for std::nan
#include <iostream> // for std::cout

int main() {
    double d = std::nan("");
    std::cout << d << std::endl; // this will print "nan"

    return 0;
}

在这段代码中,我们首先包含了<cmath><iostream>头文件,然后在main函数中,我们使用std::nan("")来生成一个NaN值,并将其存储在double类型的变量d中。最后,我们打印出d的值,将会输出"nan"。

分享一个有趣的 学习链接:https://xxetb.xet.tech/s/HY8za

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值