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;
}
相关推荐
想做小南娘,发现自己是女生喵1 小时前
【无标题】
数据结构·算法
逝水无殇1 小时前
C# 异常处理详解
开发语言·后端·c#
Kx_Triumphs3 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎3 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
玖玥拾3 小时前
C# 语言进阶(十五)C# 游戏服务端 MySQL 数据库
服务器·开发语言·网络·数据库·mysql·c#
铅笔侠_小龙虾3 小时前
Rust 学习目录
开发语言·学习·rust
Darkwanderor3 小时前
对Linux的进程控制的研究
linux·运维·c++
云泽8084 小时前
从零吃透 C++ 异常:抛出捕获、栈展开、异常重抛与编码规范详解
开发语言·c++·代码规范
轻颂呀4 小时前
约瑟夫环问题
算法