多个if语句cpp

-1 c++ if-statement

我不喜欢有很多if语句.无论如何,有一个If语句允许int等于多个数字然后执行语句,如果输入这些数字中的任何一个?

  #include <iostream>
    using namespace std;

    int main() 
    {
        int year;

        cin>>year;
        //Rat
     if (year==2008) 
     cout<<"The year "<< year <<" is the year of the Rat";

     if (year==1996)
     cout<<"The year "<< year <<" is the year of the Rat";

     if (year==1984)
     cout<<"The year "<< year <<" is the year of the Rat";

     if (year==1972)
     cout<<"The year "<< year <<" is the year of the Rat";




     //Error message
    if (year<1964)
    cout<<"Please enter a valid number.";

    if (year>2018)
    cout<<"Please enter a valid number.";
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

sco*_*001 5

大鼠的年份每12年发生一次,因此您可以使用:

if(year % 12 == 2) {
    cout << "The year " << year << " is the year of the Rat" << endl;
}
Run Code Online (Sandbox Code Playgroud)

您必须确保if (year<1964)在此之前进行范围检查(...),因为这不关心日期的早期或晚期.


然而,一个快速的谷歌搜索显示老鼠的年份实际上是1972年,1984年,1996年...所以虽然我的上述代码是你发布的代码的有效缩短,正确的代码应该是:

if(year % 12 == 4) {
    cout << "The year " << year << " is the year of the Rat" << endl;
}
Run Code Online (Sandbox Code Playgroud)

如果我们想要推广所有生肖动物,我们可以使用mod和a轻松地完成std::vector:

std::vector<std::string> zodiac_animals = {"Monkey", "Rooster", "Dog", "Pig", "Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat"};
cout << "The year " << year << " is the year of the " << zodiac_animals.at(year%12) << endl;
Run Code Online (Sandbox Code Playgroud)