float类型和double类型的比较学习
这个两种类型可以通过自己定义一个精度,如果两数相减在精度范围类,则可以认为是相等的。
#include <iostream>
#include <iomanip>
#include <cmath>
#define eps 1e-6 //自己先定义精度
#define fps 0.001f
using namespace std;
void test(double,double,double);
void test(float,float,float);
int main()
{
{
cout<<"doble类型实验结果:\n";
double i,j;
i = 2.111111;
j = 2.11111;
cout<<"直接比较大小:\n";
//float和double不能直接使用< >这些符号来比较大小,这里只是为了演示,实际应用最好别用,比如2.111>2.111在程序中是可能成立的
if (i > j)
{
cout<<setprecision(7)<<i<<"大于"<<setprecision(7)<<j<<endl;
}
else
{
cout<<setprecision(7)<<i<<"小于"<<setprecision(7)<<j<<endl;
}
cout<<"自己设置精度"<<eps<<"结果:";
test(i,j,eps);
i = 2.111111;
j = 2.1111111;
if (i > j)
{
cout<<setprecision(7)<<i<<"大于"<<setprecision(8)<<j<<endl;
}
else
{
cout<<setprecision(7)<<i<<"小于"<<setprecision(8)<<j<<endl;
}
cout<<"自己设置精度"<<eps<<"结果:";
test(i,j,eps);
}
{
cout<<"float类型实验结果:\n";
float i,j;
i = 2.111f;
j = 2.11f;
cout<<"直接比较大小:\n";
if (i > j)
{
cout<<setprecision(7)<<i<<"大于"<<setprecision(6)<<j<<endl;
}
else
{
cout<<setprecision(7)<<i<<"小于"<<setprecision(6)<<j<<endl;
}
cout<<"自己设置精度"<<fps<<"结果:";
test(i,j,fps);
i = 2.1111f;
j = 2.11111f;
if (i > j)
{
cout<<setprecision(7)<<i<<"大于"<<setprecision(8)<<j<<endl;
}
else
{
cout<<setprecision(7)<<i<<"小于"<<setprecision(8)<<j<<endl;
}
cout<<"自己设置精度"<<fps<<"结果:";
test(i,j,fps);
}
return 0;
}
void test(double di,double dj,double dp)
{
//两个数相减之后未赋值的部分可能填入一些随机数,故不一定和精度相同,只要小于精度,我们可以认为它们是相等的
if (fabs(di - dj) <= dp)
{
cout<<di<<"等于"<<dj<<endl;
}
else
{
cout<<di<<"不等于"<<dj<<endl;
}
return;
}
void test(float fi,float fj,float fp)
{
if (fabs(fi - fj) <= fp)
{
cout<<fi<<"等于"<<fj<<endl;
}
else
{
cout<<fi<<"不等于"<<fj<<endl;
}
return;
}
运行结果: