2018-03-20 创建人:Ruo_Xiao
邮箱:xclsoftware@163.com
1、bool
bool isOK = false;
if (isOK);
if (!isOK);
2、int
int i = 0;
if (i==0);
if (i!=0);
3、float和double
栗子:
#include "stdafx.h"
#include <iostream>
#include <float.h>
using namespace std;
int main()
{
double d1 = 21233134.333333;
double d2 = 21233134.333300;
cout<<"d = "<<d2 - d1<<endl;
cin.get();
return 0;
}
结果:
由于存在浮点数精度的问题,故结果不是正宗的-3.3e-5。所以,任何浮点数与数比较的时候,都不能使用“==”。
正确是使用方法如下:
#include "stdafx.h"
#include <iostream>
#include <float.h>
using namespace std;
int main()
{
double d = 0;
float f = 0;
if (fabs(d)<=DBL_EPSILON)
{
;
}
if (fabs(f)<=FLT_EPSILON)
{
;
}
cin.get();
return 0;
}
其中,DBL_EPSILON和FLT_EPSILON隶属于 float.h 头文件中。
4、指针
int *pi = 0;
if (pi==NULL);
if (pi!=NULL);
本文探讨了C++中不同数据类型的条件判断,包括bool、int、float和double,并重点讲解了如何正确地比较浮点数,避免精度问题导致的错误。
136

被折叠的 条评论
为什么被折叠?



