【问题标题】:Switch statement with integer value [closed]具有整数值的 switch 语句[关闭]
【发布时间】:2024-04-28 20:10:07
【问题描述】:

我是 C++ 的新手,我被困在 switch 语句上,因为当括号中的值是整数时它似乎没有给出输出(控制台程序以退出代码结束:0)。虽然,当我将类型更改为 char 时,相同的代码可以正常工作。 谢谢。

int main()
{
    int num1;          // argument of switch statement must be a char or int or enum
    
    cout<< "enter either 0 or 1" << "\n";
    cin>> num1;
    
    switch (num1)
    {
        case '0':
            cout<< "you entered 0" << endl << endl;
            break;
            
        case '1':
            cout<< "you entered 1" << endl << endl;
            break;
            
    }
    
}

【问题讨论】:

  • '0'0 不同。一个是字符,另一个是数字。
  • 另外,保证'0'字符不等于0的数值。
  • 一个思考练习:如果您将num1 的定义更改为char num1 并保持其余代码不变,它将起作用。

标签: c++ xcode switch-statement


【解决方案1】:

您正在打开 int,这是正确的,但您的案例不是整数 - 它们是 char,因为它们被 ' 包围。

'0' 永远不会等于 0,'1' 也永远不会等于 1。

将大小写值更改为整数。

int main()
{
    int num1;
    
    cout<< "enter either 0 or 1" << "\n";
    cin>> num1;
    
    switch (num1)
    {
        case 0:
            cout<< "you entered 0" << endl << endl;
            break;
            
        case 1:
            cout<< "you entered 1" << endl << endl;
            break;
            
    }
    
}

【讨论】:

  • 是的,我现在明白了。谢谢。
【解决方案2】:
int main()
{
    int num1;          // argument of switch statement must be a char or int or enum
    
    cout<< "enter either 0 or 1" << "\n";
    cin>> num1;
    
    switch (num1)
    {
        case 0:
            cout<< "you entered 0" << endl << endl;
            break;
            
        case 1:
            cout<< "you entered 1" << endl << endl;
            break;       
    }

}

【讨论】: