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;
}
相关推荐
@大迁世界23 分钟前
告别 Go,拥抱 Rust
开发语言·golang·rust
SEO_juper24 分钟前
Node.js 重定向链检测工具:301 跳了几跳、有没有成环,一次看清
xml·开发语言·python·node.js·json·bash
学逆向的26 分钟前
C 指针常量与常量指针
c语言·开发语言·网络安全
小郎君6581 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0
算法
低调滴开发1 小时前
3 行代码写崩一个函数?切片才是 Rust 字符串处理的正确姿势
开发语言·后端·rust
CodeYp20191 小时前
第15讲:二叉搜索树
开发语言·c++·二叉搜索树
邵奈一2 小时前
GPT-6.1 Terra速度是Sol的3倍,价格减半
算法
RaaS1002 小时前
Node.js Brotli RCE 漏洞自查指南:fetch、undici、axios 都在影响面,三分钟确认你的版本
人工智能·深度学习·算法
猫猫.1532 小时前
HashTable、HashMap、ConcurrentHashMap 核心区别总结
java·开发语言·java-ee