switch(value)设置 为int 型变量

来源:互联网 发布:淘宝静物拍照技巧 编辑:程序博客网 时间:2024/06/10 01:15

在学习C++ 的过程中,switch(value)中的value最好不要设置为bool型变量,因为bool 型变量只有0和1两种结果,而实际中value一般不只两种结果。所以就会出错,而且没有编译错误,属于逻辑错误,比较难发现。一般将value设置为int 型变量类型。




#include <iostream>

#include <stdlib.h>
#include <ctime>   // For time function
#include <cstdlib> // For rand and srand functions
using namespace std;


int main()
{


// Prompt the user to enter datas 
cout << " Please enter a, b, and c of the equation! " << endl;
double a, b, c;
cin >> a >> b >> c;


// Compute delta
double delta = b * b - 4 * a * c;
double r1, r2;


// Disbute  delta
int deltaDistube_0 = (delta > 0) ? 1 : ((delta < 0) ? 2 : 0) ;

switch (deltaDistube_0)//这里只能执行 case 0 和case 1 。因为bool 型变量只有0和1两种结果。这是容易错的地方。
{


case 0:   r1 = (-b ) / (2 * a);
     r2 = r1;
     cout << " The roots is " << r1 << endl;
     break;
case 1:   r1 = (-b + pow(delta, 0.5)) / (2 * a);
     r2 = (-b - pow(delta, 0.5)) / (2 * a);
 cout << " The roots are " << r1 << " and " << r2 << endl;
 break;
case 2:   cout << " The equation has no roots! " << endl;
     break;
default: return 0;

}







// Pause the windows
cout << endl;
system(" pause ");
return 0;


}
0 0