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;
}
相关推荐
0+11111 小时前
算法 --哈希表
数据结构·算法·散列表
灯澜忆梦11 小时前
【面向对象编程c++】| 数组与函数
java·数据结构·c++
我命由我1234511 小时前
Android 广播 - 组件通信
android·java·开发语言·android studio·android jetpack·android-studio·android runtime
前端 贾公子11 小时前
LangGraph == 图的状态(State)管理 (中)
开发语言·数据库·python
起个名字费劲死了12 小时前
VisionMaster 十二点标定+单点抓取
c++·visionmaster
李福春12 小时前
斗破Google ADK Java苍穹-第2境斗者-凝旋筑基-Java环境
java·开发语言·gemini·llmagent·深圳同盟·腾讯云架构师技术同盟·adk java
Interview Aid11212 小时前
Stripe VO 面经汇总:5 轮面试题目与考察重点
算法
EEET智选12 小时前
科技晨间速报 | AI 安全警钟、开源新模型与苹果智能家居
人工智能·科技·算法·机器学习·ai
挖掘狂人12 小时前
哈希算法:一根看不见的 "指纹",如何撑起整个互联网
算法·程序员·掘金技术征文
鶴哥只手遮天12 小时前
ecRad 1.5.0 算法原理详解
算法·开源