Cpp中比较两个浮点数的大小是否相等

#include <iostream>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cfloat>
//头文件<float.h>中定义了
// #define FLT_EPSILON   1.19209290E-07F 用于比较float
//  DBL_EPSILON   2.2204460492503131e-016 用于比较double
// #define LDBL_EPSILON  1.084202172485504E-19 用于比较long double

using namespace std;

int main()
{
    //需要比较两个浮点数的大小
    float fA = 1.19830706;
    float fB = 1.19830703;
    //float 精确不了最后一位,即1e-8,double类型可以
    cout << fixed << setprecision(8) << fA << endl << fB << endl; // 1.19830704  1.19830704
    //不要用直接 == 去比较两个浮点数
    cout  << boolalpha << (fA==fB) << endl; //true
    //可以用 abs(a-b) < 非常小的数
    cout << (abs(fA-fB) < FLT_EPSILON) << endl;//true
    cout << (abs(fA-fB) < 1e-10) << endl; //true,自己定义误差好像没有用
    //但可以转化为字符串比较
//    char buffer[10];
//    sprintf(buffer, "%12.8f", fB); //在<stdio.h>中
//    cout << buffer << endl;

    //定义一个stringstream对象
    stringstream sstr;
    sstr << fixed << setprecision(8) << fA;
    string strA;
    sstr >> strA;
    //清空stringstream对象,开始第二轮转换
    sstr.clear();
    sstr << fB;
    string strB;
    sstr >> strB;
    if(strA == strB)
        cout << fA << "等于" << fB << endl;
    //将字符串转换为浮点数
    stringstream sstr2;
    string a("1.9635");
    sstr2 << a;
    float b=0;
    sstr2 >> b;
    cout << setiosflags(ios_base::floatfield) << b << endl; // 1.9635
    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/htj10/p/9317789.html
今日推荐