C++浮点数比较

根据资料,C++浮点数计算时存在精度误差,在一些情况下比较浮点数可能应使用特定的比较函数;

cpp 复制代码
#include "stdafx.h"
#include<iostream>

using namespace std;

#define EPS 1e-9

int main(int argc, char* argv[])
{

	double a = 0.3;
	double b = 0.1 + 0.2;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "a-b = " << a - b << endl;

	if (abs(a - b) < EPS)  // 比较浮点数需考虑精度误差
	{
		cout << "a and b are the same" << endl;
	}
	return 0;
}
相关推荐
deepin_sir1 小时前
10 - 函数
开发语言·python
z落落2 小时前
C#String字符串
开发语言·c#·php
wljy12 小时前
二、进制状态转换
linux·运维·服务器·c语言·c++
猫头虎-前端技术2 小时前
JS 作用域与闭包:从变量提升到闭包陷阱的超详细解析
开发语言·javascript·云计算·bootstrap·ecmascript·openstack·perl
云泽8082 小时前
笔试算法 -位运算篇(二):从唯一字符到消失数字
c++·算法·位运算
枫叶林FYL2 小时前
项目十:事件溯源仓储管理系统(WMS)仿真实现
开发语言·python
ʚ希希ɞ ྀ2 小时前
不同路径|| -- dp
算法
繁华落尽,倾城殇?3 小时前
[C++11] : atomic,nullptr,default/delete,enum class
开发语言·c++·c++11·nullptr·atomic·enum class·default/delete
01_ice3 小时前
C语言数据在内存中的存储
c语言·开发语言
代码村新手3 小时前
C++-二叉搜索树
开发语言·c++