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;
}
#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;
}
相关文章推荐
- PowerBuilder命令行编译详解[1]
- 重写UIButton的图片、title Frame
- JAVA可阻塞队列-ArrayBlockingQueue子类BlockingQueue的应用,使用它来实现子线程打印10次,主线程打印100次,如此反复
- easyui datebox只显示年月
- 《iOS Human Interface Guidelines》——iCloud
- UGUI中的InputField下的placeholder的作用?
- GUID
- JAVA可阻塞队列-ArrayBlockingQueue
- UITextField使用时文字向下偏移问题
- Contacts(CNSaveRequest)
- Mobileye's quest to put Deep Learning inside every new car
- clouder manager uuid文件导致无法添加主机问题
- ceph存储 UIO 子系统结构介绍
- UIView的基本属性和方法
- UIsearchController
- iOS 视图控制器(UIViewContr…
- iOS开发中UIImageView控件的常用操作整理
- Native Libraries Guide
- iOS中的UINavigationController导航栏视图控制器的简单应用
- Android UI布局之用户界面概述