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;
}
相关推荐
呱呱巨基12 小时前
CMake基础
linux·c++·笔记·学习
程序员-Benothing13 小时前
如何实现高并发系统订单30分钟自动关闭?
开发语言·c#·wpf
佳児素花痴╮14 小时前
树的基础知识与查找排序算法
数据结构·算法
郝学胜-神的一滴14 小时前
Python 高级编程 026:内置数据结构之骈文纵论
开发语言·数据结构·python·程序人生·软件工程
lueluelue4721 小时前
LeetCode:链表
算法·leetcode·链表
隐积1 天前
3.1.7.Qt容器大家族(3):QVariant——万能盒子
开发语言·qt
橘子汽水1681 天前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
huameinan狮子1 天前
Adaboost算法原理与计算实例
算法
Tri_Function1 天前
动态规划DP1(c++)
c++
别怪我很水1 天前
API中提供了VelocityTracker类用于计算触摸事件MotionEvent的速度,而其内部默认使用的方法就是最小二乘法,本 ...
算法·gitee·最小二乘法