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;
}
相关推荐
专注仿真5 小时前
仿真智能体训练(评估篇):基于蒙特卡洛批量对抗的评估算法详解与实战
算法·仿真·评估·afsim智能体·仿真训练
默 语6 小时前
HarmonyOS7 事件分发控制(二):onTouchIntercept 镂空玻璃卡——圆内自己接,圆外放行
android·java·开发语言
Amumu121387 小时前
TypeScript学习: 基础知识(二)
开发语言·typescript·ecmascript
derek19977 小时前
软考软件设计师:B-树和 B+树的区别、线性探查法查找时到底比较了谁
c语言·c++·计算机网络·软件工程·学习方法
sharemylove7 小时前
Java 异常与常用类 学习笔记
java·开发语言·经验分享·笔记·学习
小灰灰搞电子8 小时前
C 语言基础:动态内存管理详解
c语言·开发语言
打工仔折腾 AI8 小时前
L3 静态源码取证|工程评测:python-oracledb 驱动评估中的样本偏差陷阱
开发语言·人工智能·后端·python·性能优化
fqbqrr8 小时前
2612C++,C++量钢问题
c++
Amumu121388 小时前
TypeScript学习: 进阶知识
开发语言·学习·typescript
充电zcx9 小时前
C++ 复习:stack、queue 与仿函数——容器适配器、priority_queue 与 deque 的取舍
c++·queue·仿函数·stack·priority_queue