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;
}
相关推荐
KookeeyLena82 分钟前
如何限制任何爬虫爬取网站的图片
开发语言·c++·爬虫
m_Molly15 分钟前
vs2022配置opencv==4.9.0(C++)
c++·opencv
yanyanwenmeng22 分钟前
matlab基础
开发语言·算法·matlab
##晴天小猪24 分钟前
ByteTrack多目标跟踪流程图
人工智能·算法·目标检测·机器学习·目标跟踪
charon877833 分钟前
Unreal Engine 5 C++: 编辑器工具编写入门(中文解释)
c++·ue5·编辑器·游戏引擎·虚幻
Ddddddd_15835 分钟前
C++ | Leetcode C++题解之第421题数组中两个数的最大异或值
c++·leetcode·题解
末央&38 分钟前
【C++】内存管理
java·开发语言·c++
ly-how39 分钟前
leetcode练习 二叉树的层序遍历
算法·leetcode
不是仙人的闲人41 分钟前
Qt日志输出及QsLog日志库
开发语言·数据库·qt
八了个戒1 小时前
【TypeScript入坑】TypeScript 的复杂类型「Interface 接口、class类、Enum枚举、Generics泛型、类型断言」
开发语言·前端·javascript·面试·typescript