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;
}
相关推荐
Queenie_Charlie3 小时前
小陶的疑惑2
数据结构·c++·树状数组
无小道3 小时前
Qt——QWidget
开发语言·qt
时艰.3 小时前
Java 并发编程之 CAS 与 Atomic 原子操作类
java·开发语言
梵刹古音4 小时前
【C语言】 函数基础与定义
c语言·开发语言·算法
筵陌4 小时前
算法:模拟
算法
梵刹古音4 小时前
【C语言】 结构化编程与选择结构
c语言·开发语言·嵌入式
Yvonne爱编码4 小时前
JAVA数据结构 DAY3-List接口
java·开发语言·windows·python
一方_self4 小时前
了解和使用python的click命令行cli工具
开发语言·python
南宫码农4 小时前
我的电视 - Android原生电视直播软件 完整使用教程
android·开发语言·windows·电视盒子
Queenie_Charlie5 小时前
小陶与杠铃片
数据结构·c++·树状数组