如果声明“您的代码永远不会被执行”

时间:2016-03-22 16:01:53

标签: c++

底部的if else不起作用;它说宠物并不存在。

void checkIn ()
{

    int roomNum = 0;
    int party = 0;
    char pets;
    char smoke;

    cout << "----------------------------" << endl;
    cout << "Welcome to Shrek's Swamp Inn" << endl << endl;

    cout << "How many people are In your party? " << endl;
    cin >> party;

    cout << "Do you have pets? (Y/N)" << endl;
    cin >> pets;

    switch (pets)
    {
        case 'Y' : case 'y':
            cout << "GTLO" << endl;
            break;
        case 'N' : case 'n':
            cout << "cool cool" << endl;
            break;
        default :
            cout << "User error" << endl;
    }

    cout << "Do you want a smoke room? (Y/N) " << endl;
    cin >> smoke;

    switch (smoke)
    {
        case 'Y' : case 'y':
            cout << "GTLO" << endl;
            break;
        case 'N' : case 'n':
            cout << "cool cool" << endl;
            break;
        default :
            cout << "User error" << endl;
    }

    if((pets == 'Y' || 'y') && (smoke == 'Y' || 'y')){
        roomNum = rand() % 4 + 1;
        cout << "Your room is " << roomNum << "S" << endl;
    }
    else if((pets == 'Y' || 'y') && (smoke == 'n' || 'N')){
        roomNum = rand() % 8 + 5;

        cout << "Your room is " << roomNum << "P" << endl;
    }
    else if((pets == 'n' || 'N') && (smoke == 'n' || 'N'));{
        roomNum = rand() % 15 + 9;

        cout << "Your room is " << roomNum << "R" << endl;
    }

}

2 个答案:

答案 0 :(得分:8)

您应该更改if条件

(pets == 'Y' || 'y')

(pets == 'Y' || pets == 'y')

否则,对于if条件,'y'(作为非零值)将始终评估为true,然后(pets == 'Y' || 'y')也始终为true

对于所有其他条件,它都是一样的。

答案 1 :(得分:4)

添加到songyuanyao&#39; answer,您还有另一种语法错误

else if((pets == 'n' || 'N') && (smoke == 'n' || 'N'));{

请注意语句末尾的分号;,您需要删除此