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;
}

  

转载于:https://www.cnblogs.com/htj10/p/9317789.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值