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;
}
相关推荐
郑州光合科技余经理5 小时前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 小时前
matlab画图工具
开发语言·matlab
dustcell.6 小时前
haproxy七层代理
java·开发语言·前端
norlan_jame6 小时前
C-PHY与D-PHY差异
c语言·开发语言
ZPC82106 小时前
docker 镜像备份
人工智能·算法·fpga开发·机器人
ZPC82106 小时前
docker 使用GUI ROS2
人工智能·算法·fpga开发·机器人
琢磨先生David6 小时前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
哇哈哈20216 小时前
信号量和信号
linux·c++
颜酱6 小时前
栈的经典应用:从基础到进阶,解决LeetCode高频栈类问题
javascript·后端·算法
多恩Stone6 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc