您的位置:首页 > 产品设计 > UI/UE

switch(value)设置 为int 型变量

2016-01-14 10:24 399 查看
在学习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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: