2007年3月14日星期三

c++食谱第三章部分笔记之三

食谱3.3 检验一个字符串是否为一个有效的数字
问题:
有一个字符串,想检验其是否为有效的数字。
方案:
使用boost库中的lexical_cast函数模板。
食谱3.4 以一定的精度比较两个浮点数
问题:
以一定的精度比较浮点数,比如精度为0.0001的情况下,3.33333和3.333333333的大小。
方案:
自写比较函数来设置其精度。


#include<iostream>
#include<cmath>
using namespace std;
bool doubleEquals(double left,double right,double epsilon){
return(fabs(left-right)<epsilon);
}
bool doubleLess(double left,double right,double epsilon,bool orequal=false){
if(fabs(left-right)<epsilon){
return (orequal);
}
return(left<right);
}
bool doubleGreater(double left,double right,double epsilon,bool orequal=false){
if(fabs(left-right)<epsilon){
return(orequal);
}
return(left>right);
}
int main(){
double first=0.333333333;
double second=1/3.0;
cout<<first<<endl;
cout<<second<<endl;
cout<<boolalpha<<(first==second)<<endl;
cout<<doubleEquals(first,second,.0001)<<endl;
cout<<doubleLess(first,second,.0001)<<endl;
cout<<doubleGreater(first,second,.0001)<<endl;
cout<<doubleLess(first,second,.0001,true)<<endl;//此为不大于
cout<<doubleGreater(first,second,.0001,true)<<endl;//此为不小于
}

没有评论: