根据资料,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;
}