zoukankan      html  css  js  c++  java
  • 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;
    }
    

      

    常记溪亭日暮,沉醉不知归路。兴尽晚回舟,误入藕花深处。争渡,争渡,惊起一滩鸥鹭。

    昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。
  • 相关阅读:
    第一行代码--笔记(1)
    iOS UITableView深入
    iOS 数据库主键重复,依然可以插入
    UILabel文本高度自适应 不同系统出现问题
    UIlabel上的文字 距上 居左 对齐
    UILabel 自定义字体
    【整理】--VC 编译整理
    【整理】--【内核模块】简单例子,编译加载
    【原创】-- uboot,kennel,fs,rootfs 编译制作
    【原创】-- nfs安装配置及使用,挂载根文件系统
  • 原文地址:https://www.cnblogs.com/htj10/p/9317789.html
Copyright © 2011-2022 走看看