c++ - 如果语句 "Your Code Will Never Be Executed"

标签 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;
    }

}

最佳答案

你应该改变if条件

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

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

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

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

关于c++ - 如果语句 "Your Code Will Never Be Executed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36159380/

相关文章:

c++ - 用于在容器中迭代一系列角度的成语?

c++ - 当参数在初始化列表时不可用时如何初始化成员对象?

c++ - glibc 上的 valgrind 输出在 C++ 中检测到错误

c++ - QGLViewer 的替代品

c++ - 自定义 std::fstream、std::filebuf 的上溢和下溢函数不会为每个字符调用

c++ - 链接 c/c++ 的问题

c++ - 函数指针指针数组

c++ - 空 std::list 在调用析构函数时抛出异常

c++ - 套接字 recv() 一次一个字节

c++ - g++ 在编译时挂起