可以用case范围切换语句吗?
Switch statements with case ranges, is it possible?
所以我在一个开关语句工作,但我不太确定如果我这样做是正确的。这是我使用c++ (visual studio 2010)编写的第一个小程序,我不确定我是否正确使用了switch语句。我要做的是让一个人输入数字。我设置了一个计数器来计算输入的数量,并且我有一个运行总数来输出所有输入数字的总和。
while (additional_input > 0)
{
cout << "Enter additional number, use 0 to exit: ";
cin >> additional_input ;
count ++; //increment the counter
//Do the addition
sum += additional_input; //sum up all inputs
} //end of the while statement
switch (sum){ //this is where I get into trouble
case 0-99: cout << "nn"; //original question, can I do this?
cout << "Thank you. The sum of your numbers is........: " << sum << endl ;
cout << "The total number of inputs read..............: " << count << endl;
cout << "The sum of your numbers is less than 100" << endl;
return 0;
break;
case 100: cout << "nn"; //and so on
所以我的问题是这是否可能。我可以用这个箱子吗?
标准c++不允许大小写范围,在你的代码中,0-99
将最终被评估为0
减去99
,这意味着你所拥有的基本上是:
case -99:
另一种选择是使用if语句来代替
case 0-99
将成为:
if( sum >= 0 && sum <= 99 )
{
}
包括gcc
在内的一些编译器提供大小写范围作为扩展,但这会使您的代码非标准且不可移植,并且由于您使用的是Visual Studio,因此可能不适用。
我其实算出来了。最好是根据金额来定案。因为我有三种情况,我只是让它根据我之前得到的总数来选择情况。下面是我的代码:
while (additional_input > 0)
{
cout << "Enter additional number, use 0 to exit: ";
cin >> additional_input ;
count ++; //increment counter
//Do the addition
sum += additional_input; //sum up all inputs
} //end of the while statement
if (sum < 100){ //set condition for option 1
option =1;}
else if (sum == 100){//set condition for option 2
option =2;}
else if (sum > 100)
{option = 3; //last resort option 3
}
switch (option)
{
case 1: cout << "nn";//new line
cout << "Thank you. The sum of your numbers is........: " << sum << endl ;
cout << "The total number of inputs read..............: " << count << endl;
cout << "The sum of your numbers is less than 100" << endl;
break;
case 2: cout << "nn";//new line
很有魅力。
相关文章:
- "1L << count"是什么意思?如何使用超出"unsigned long long int? "范围的语句编号打印?
- C++带有 while 语句范围捕获的 if 语句中的错误
- 这个基于范围的'for'语句需要一个合适的函数,但找不到任何函数
- C++ if 语句范围内的宏未编译
- 为什么此范围基于语句返回一个数字太低的范围
- 为什么所有可能的整数都"true"在 C++ 的 if 语句内的 long int 范围内,而 0 不是?
- 为什么在基于initializer示例的基于范围内的语句中,f()
- 重构使用 if 语句的重复范围检查
- C++ 在 switch 语句中超出范围
- 删除"超出矢量误差范围"的打印语句后输出不同的根本原因
- C 在开关语句中使用特定类和枚举范围
- 我如何为内部列表提供基于范围的语句?(C )
- 范围切换语句
- switch 语句中的奇数变量范围
- 条件语句,用于验证事务模块(.cpp)标头中#define(d)整数提供的范围
- 使用 if if 语句检查 C++ 中的范围
- 为什么基于范围的 for 语句通过 auto&& 获取范围?
- 语句的嵌套范围是否严格合法
- 如何制作增强多指数复合范围语句,等效于x和y
- 为什么对“for”语句范围有特殊规则