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;
}
相关推荐
被子你放开我18 分钟前
CRMEB PHP多商户升级4.0太麻烦了
开发语言·php
阿里嘎多学长18 分钟前
2026-06-01 GitHub 热点项目精选
开发语言·程序员·github·代码托管
醒醒该学习了!33 分钟前
Anaconda安装教程+第一个python例子
开发语言·python
8Qi81 小时前
LeetCode 23. 合并 K 个升序链表 —— 小顶堆(PriorityQueue)
数据结构·算法·leetcode·链表·
QiLinkOS1 小时前
《打破“用爱发电”:一种基于 Gitee 与时间戳的开源权益分配机制探索》
c语言·数据结构·c++·科技·算法·gitee·开源
Irissgwe1 小时前
c++STL--string类
c++·stl·string
松间听晚2 小时前
Agentic RL 环境和代码学习:以HGPO为例
算法
Irissgwe2 小时前
c++类型转换
c++·类型转换·explicit·static_cast·const_cast·dynamic_cast·rtti
智者知已应修善业2 小时前
【51单片机用T0定时器方式1,实现0.5S的时间间隔实现第一次一个灯亮、第二次二个灯亮,直到全部灯亮,然后重复整个过程】2023-12-29
c++·经验分享·笔记·算法·51单片机