博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Cpp中比较两个浮点数的大小是否相等
阅读量:7170 次
发布时间:2019-06-29

本文共 1304 字,大约阅读时间需要 4 分钟。

#include 
#include
#include
#include
#include
#include
//头文件
中定义了// #define FLT_EPSILON 1.19209290E-07F 用于比较float// DBL_EPSILON 2.2204460492503131e-016 用于比较double// #define LDBL_EPSILON 1.084202172485504E-19 用于比较long doubleusing 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); //在
中// 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

你可能感兴趣的文章
第二次作业
查看>>
Mysql主从复制
查看>>
高斯消元法解非奇异线性方程组的MATLAB程序
查看>>
CSS3 3d环境实现立体 魔方效果代码
查看>>
全面总结sizeof的用法(定义、语法、指针变量、数组、结构体、类、联合体、位域位段)...
查看>>
python2升级到python3
查看>>
做好该做的把未来交给明天
查看>>
脚本里添加crontab的方法
查看>>
configure:error: Package requirements (libffi >= 3.0.0) were not met
查看>>
java 抽象类与接口的区别
查看>>
Linux驱动模块编译模板
查看>>
我的友情链接
查看>>
MySQL 5.6.12 安装
查看>>
MCSA&MCP认证证书
查看>>
我的友情链接
查看>>
进阶篇第五期:UIScrollView的那点事儿
查看>>
CSS系列:CSS中盒子模型
查看>>
2017网络安全产业研究报告学习笔记
查看>>
AES&FEC GPON中的加密与纠错
查看>>
python 字典嵌套
查看>>