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;
}
相关推荐
timeDifference₇1 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu2 小时前
python:DecisionTree
开发语言·后端·python·算法
ShineWinsu2 小时前
对于Qt:事件的解析
c++·qt·面试·笔试·gui·客户端·事件
geovindu3 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
闻缺陷则喜何志丹4 小时前
【数论】P10136 [USACO24JAN] Cowlendar S|普及+
c++·数学·数论·洛谷
apcipot_rain5 小时前
某游戏公司C++游开实习 机试复盘
c++·游戏
AllData公司负责人6 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
武子康7 小时前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习
炸膛坦客7 小时前
单片机/C/C++八股:(三十七)指针数组 和 数组指针
c语言·开发语言·c++