多个if语句cpp

时间:2018-04-24 16:54:49

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

3 个答案:

答案 0 :(得分:5)

大鼠的年份每12年发生一次,所以你可以使用:

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

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

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

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

如果我们想要概括所有生肖动物,我们可以使用mod和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;

答案 1 :(得分:4)

您可以使用逻辑运算符:

{node.image[0].resolutions.src && (
  <Img
    style={{ margin: 0 }}
    resolutions={node.image[0].resolutions}
  />
)}

您还可以使用if (year == 2008 || year == 1996 || year == 1984 || year == 1972) ,并在案例之间不使用switch/case时利用这种突破行为:

break

但最简单的方法是利用中国十二生肖中的12年周期,通过算术和向量来实现这一目标,因此您不必明确列出年份(可能会出现多年的错误,正如你所做的那样)。

switch (year) {
case 2008:
case 1996:
case 1984:
case 1972:
    cout >> "The year " << year << " is the year of the Rat" << endl;
    break;
    ...
}

答案 2 :(得分:0)

如果要检查的数据集是有限的,并且您确实希望最小化所有类型的分支结构,则可以始终使用容器和std::algorithm find。以下是一个示例(您可以在其上阅读更多内容here):

#include <iostream>
#include <algorithm>
#include <vector>

int main ()
{
  int myints[] = { 10, 20, 30, 40 }; // finite set of values
  std::vector<int> myvector (myints, myints + 4);
  std::vector<int>::iterator it;

  it = find (myvector.begin(), myvector.end(), 30);
  if (it != myvector.end()) // Only one if
    std::cout << "Element found in myvector: " << *it << '\n';
  else
    std::cout << "Element not found in myvector\n";

  return 0;
}

这将始终归结为std::find(或任何其他算法,具体取决于您的情况)和一个if的调用。