默认值仅适用于 8 和 9.之后,它使用第一个数字并将其视为 1,2,3

default only works for 8 and 9. after that it uses the first number and treats it as a a 1,2,3

本文关键字:数字 第一个 适用于 之后 默认值      更新时间:2023-10-16

default除了数字8和9之外不起作用。10 及以上它使用第一个整数,将其视为完全忽略其后面的第二个数字的情况。请帮忙

#include <iostream> 
#include <string>
using namespace std;
int main ()
{
     char day;
        cout << " Enter day of the week " << endl;
        cin >> day;
        switch (day)
   {  
        case '1' : case '6' : case '7' :
           cout << "weekend";
            break;
    case '2' : case '4' :
        cout << "going to C++ Class";
        break;
    case '3' : case '5' :
        cout << "studying for C++ Class";
        break;
    default :
        cout << "invalid day number";

}

    system("pause");
    return 0;

}

当你写的时候

char day;
cin>>day;

它只接受输入中的一个字符。您应该将 day 声明为整数,您的问题将得到解决。

您只在 day 变量中存储一个字符,因为它被声明为 char 。 将其更改为 int ,并将 switch 语句中的大小写更改为int值。

#include <iostream> 
#include <string>
using namespace std;
int main ()
{
    int day;
    cout << " Enter day of the week " << endl;
    cin >> day;
    switch (day)
    {  
        case 1:
        case 6:
        case 7:
            cout << "weekend";
            break;
        case 2:
        case 4:
            cout << "going to C++ Class";
            break;
        case 3:
        case 5:
            cout << "studying for C++ Class";
            break;
        default :
            cout << "invalid day number";
    }
    system("pause");
    return 0;
}

您的问题是将输入存储在char中。

由于您将day存储为 char,因此它仅足够大以存储任何输入的第一个字符。当你输入1(或2,或3等(时,这很好,因为输入只有一个字符。当您输入一个具有多个数字的数字时,只能存储第一个字符 - 例如,如果您输入 10 ,则只有空间存储1

要解决此问题,您应该对 day 使用更合适的数据类型。使用int或类似的东西可能是最好的,因为这会给你足够的空间来容纳大值。因此,换句话说,将char day;更改为int day;

但是,如果您这样做,则需要更改case语句中的值以匹配 - 由于您不再比较字符,因此您也需要将它们更改为整数(例如,将'0'更改为仅0(。

 char day;
    cout << " Enter day of the week " << endl;
    cin >> day;

您的代码说从标准输入中读取一个字符。如果这不是您想要执行的操作,请更改代码。

在决定变量的数据类型时,您需要非常小心,因为每种数据类型都有其固有属性。就像这里指出的每个人一样,您需要将数据类型从"char"更改为"int"。