切换语句范围的语句,是否可能?

时间:2014-03-20 02:50:23

标签: c++ visual-studio-2010 switch-statement

所以我正在处理一个switch语句,但我不确定我是否正确这样做。这是我第一个使用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 << "\n\n"; //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 << "\n\n"; //and so on

所以我的问题是这是否可行。我可以用这个案例吗?

2 个答案:

答案 0 :(得分:3)

标准C ++不允许案例范围,在您的代码中0-99最终会被评估为0减去99,这意味着您拥有的内容基本上是:

case -99:

另一种方法是使用 if语句代替:

case 0-99

会变成:

if( sum >= 0 && sum <= 99 )
{

}

某些编译器(包括gcc)提供case ranges作为扩展名,但这会使您的代码非标准且不可移植,因为您使用Visual Studio可能不适用。

答案 1 :(得分:-1)

我实际想出来了。最好根据总和设置一个案例。由于我有3个案例与我合作,我只是根据我之前获得的总数选择了案例。以下是我的代码:

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 << "\n\n";//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 << "\n\n";//new line

像魅力一样工作。