if/else语句中存在多个条件

Multiple conditions in if/else statement?

本文关键字:条件 存在 else 语句 if      更新时间:2023-10-16

我还是个初学者,所以如果经常问这些问题,我很抱歉。我搜索了好几次,但都找不到合适的答案。以下是我的两个主要问题:

我正在构建一个简单的计数程序,允许用户按1、2、3等进行计数。首先,这里是我的函数代码:

int Count::numOne() {
cout << "You chose to count by 1! Press "Y" to continue counting. Press "N" to return to the main page." << endl;
while (cin >> yesNo) {
    if ((yesNo == 'y') || (yesNo == 'Y')) {
        ++one;
        cout << one << endl;
    }
    else if ((yesNo == 'n') || (yesNo == 'N')) {
        cout << "User selected no." << endl; //How do I return back to the main function?
}
    else {
        cout << "Please enter either "Y" or "N"." << endl;
    }
}
return 0;
}
  1. 我已经让程序在大部分情况下正常运行,但对于if/else条件,是否有"更好"或更干净的语法可供使用?我觉得

    if ((yesNo == 'y') || (yesNo == 'Y'))
    

    具有不必要的冗余并且可以更清洁。

  2. 此外,如果用户输入"n"或"n",我如何返回主函数并从头开始程序?

1)从编译代码的角度来看,进行这两个比较都很好,并且清楚地调用每个比较是非常可读的

2) 您想要的是一个break;表达式来突破while循环

您想要类似以下内容:

string yes {"Yy"};
cout << "You chose to count by 1! Press "Y" to continue counting. Press "N" to return to the main page." << endl;
while (cin >> yesNo) {
    if (yes.find_first_of(yesNo) != string::npos) {
        ++one;
        cout << one << endl;
    }
    // ... other stuff
}
  1. 在这种情况下,operator==调用周围的括号是不必要的,请参阅运算符优先级。除非你想制作一个自定义的比较函数并使用它,否则这就是它的全部

    #include <cctype>
    // will accept both c and option as lowercase or uppercase
    bool isOption(char c, char option)
    {
        return std::tolower(c) == std::tolower(option);
    }
    
  2. 只是循环中的break,所以它是return0,或者return(可能是其他)值,因为你在一个函数中。