linux系统c/c++中的inf和nan

linux系统c/c++中的inf和nan

测试环境:Ubuntu16.04
inf表示无穷大的数。
nan表示"not a number",不是一个整数。

  1. 判断表达式的结果是否为inf
#include <iostream>
#include <math.h>
int main()
{
	float a;
	a = INFINITY;
	std::cout << "a:" <<a << std::endl;
	// 方式一
	if(isfinite(a))
	{
		std::cout << "a is not inf" << std::endl;
	}
	else
	{
		std::cout << "a is inf" << std::endl;
	}
	// 方式二
	if(isinf(a))
	{
		std::cout << "a is inf" << std::endl;
	}
	else
	{
		std::cout << "a is not inf" << std::endl;
	}

	float b;
	b = NAN;
	std::cout << "b:" <<b << std::endl;
	if(isnan(b))
	{
		std::cout << "b is not a number" << std::endl;
	}
	else
	{
		std::cout << "b is a number" << std::endl;
	}

	return 0;
}
a:inf
a is inf
a is inf
b:nan
b is not a number
  1. 根据读入string数据的值确定float的值
#include <iostream>
#include <math.h>
#include <stdlib.h> 
int main()
{
	std::string a, b;
	float c, d;
	a = "111";
	b = "nan";
	std::cout << "a:"  << a << std::endl;
	std::cout << "b:"  << a << std::endl;
	// 根据读入string数据的值确定float的值
	if(a == "inf")
	{
		c = INFINITY;
	}
	else
	{
		c = float(atof(a.c_str()));
	}
	std::cout << "c:"  << c << std::endl;
	// 根据读入string数据的值确定float的值
	if(b == "nan")
	{
		d = NAN;
	}
	else
	{
		d = float(atof(b.c_str()));
	}
	std::cout << "d:"  << d << std::endl;
	return 0;
}

输出

a:111
b:111
c:111
d:nan

版权声明:本文为weixin_43996161原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。