不可将浮点变量用“==”或“!=”与任何数字比较

不可将浮点变量用“==”或“!=”与任何数字比较。

千万要留意,无论是 float 还是 double 类型的变量,都有精度限制。所以一定要避 免将浮点变量用“==”或“!=”与数字比较,应该设法转化成“>=”或“<=”形式。

假设浮点变量的名字为 x,应当将 if (x == 0.0) // 隐含错误的比较 转化为 if ((x>=-EPSINON) && (x<=EPSINON)) 其中 EPSINON 是允许的误差(即精度)。

 1 #include <iostream>
 2 
 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 4 using namespace std;
 5 //基类First
 6 class First {
 7     int val1;
 8 public:
 9     SetVal1(int v) {
10         val1=v;
11     }
12     void show_First(void) {
13         cout<<"val1="<<val1<<endl;
14     }
15 };
16 //派生类Second
17 class Second:public First {   //默认为private模式
18     int val2;
19 public:
20     void SetVal2(int v1,int v2) {
21         SetVal1(v1);     //可见,合法
22         val2=v2;
23     }
24     void show_Second(void) {
25     // cout<<"val1="<<val1<<endl; 不能访问First私有成员
26         show_First();
27         cout<<"val2="<<val2<<endl;
28     }
29 };
30 
31 int main(int argc, char** argv) {
32         Second s1;
33     //调用Second类定义的成员函数
34     s1.SetVal2(2,3);    
35     cout<<"s1.show_Second():"<<endl;
36     s1.show_Second();
37 
38     //调用First类定义的成员函数
39     s1.SetVal1(10);  
40     cout<<"s1.show_First():"<<endl;    
41     s1.show_First(); 
42     return 0;
43 }
原文地址:https://www.cnblogs.com/borter/p/9413476.html