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

      

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

    昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。
  • 相关阅读:
    A1052. Linked List Sorting (25)
    A1032. Sharing (25)
    A1022. Digital Library (30)
    A1071. Speech Patterns (25)
    A1054. The Dominant Color (20)
    A1060. Are They Equal (25)
    A1063. Set Similarity (25)
    电子码表
    矩阵键盘
    对象追踪、临时对象追踪、绝对坐标与相对坐标
  • 原文地址:https://www.cnblogs.com/htj10/p/9317789.html
Copyright © 2011-2022 走看看