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;
}
相关推荐
zhanghaha131415 小时前
C# 系列教程_7 判断语句(分支)保姆级精讲
开发语言·c#
apcipot_rain15 小时前
C++转Java日记(02)
java·开发语言·c++
杜 硕16 小时前
从零开始的C++生活——第七讲——02
开发语言·c++·生活
zhanghaha131416 小时前
C# 系列教程_8 循环语句 保姆级精讲(面向新手)
开发语言·c#
Rabitebla1 天前
【Linux 底层原理】进程(十):进程等待详解---从僵尸进程到 wait、waitpid 与 status
linux·c++·笔记·学习·visual studio
麦麦麦当劳大王1 天前
【油猴脚本】Boss直聘 岗位职责复制
开发语言·前端·javascript
starzy19901 天前
深入理解Scala Map:从实现原理到工程实践
开发语言·后端·scala
只睡四小时1 天前
Three.js Sub-tick:漏判 60.7%→0
开发语言·javascript·性能优化·ecmascript·游戏开发·three.js·碰撞检测
码农小河661 天前
基于SSM+JSP的高校专业信息管理系统【附源码+数据库】
java·开发语言·数据库
西西弗Sisyphus1 天前
C++ 超时互斥锁(Timed Mutex):std::timed_mutex 与 std::unique_lock
c++