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;
}
相关推荐
mmmmath_33 分钟前
LeetCode.018.四数之和
数据结构·算法·leetcode
AIGCmagic社区4 分钟前
腾讯混元 AuK 技术报告拆读:1.5B 统一语音生成与编辑,蒸馏后 4 步无 CFG 提速 4.5 倍
人工智能·算法·aigc·ai多模态
大熊背5 分钟前
基于照明色度表征的颜色恒常性的白平衡算法实现
算法·白平衡·色温·色度坐标·普朗克曲线
Yyyyyy~7 分钟前
【java】类和对象
java·开发语言
高亦真12 分钟前
今天是学习嵌入式的第38天
linux·学习·算法
蒸蒸yyyyzwd19 分钟前
cpp 选手备战秋招学习笔记 day36
c++
草莓熊Lotso19 分钟前
【Redis 进阶】主从复制深度解析:从配置落地到 PSYNC 同步原理
linux·开发语言·网络·数据库·redis·缓存·php
用户695861067271132 分钟前
从源码到加载器:__attribute__((constructor)) / __attribute__((destructor))的跨平台实现原理详解
c++
Joy T35 分钟前
Spring AI 2.0 进阶入门:Workflow、Routing、Task State 与可控 Agent
开发语言·人工智能·workflow·routing·springai·orchestrator·evaluator
重生之小比特38 分钟前
【Java SE】抽象类和接口
java·开发语言