可以用case范围切换语句吗?

Switch statements with case ranges, is it possible?

本文关键字:语句 范围 case      更新时间:2023-10-16

所以我在一个开关语句工作,但我不太确定如果我这样做是正确的。这是我使用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

很有魅力。