If statement 为什么我的If-else语句不起作用?

If statement 为什么我的If-else语句不起作用?,if-statement,If Statement,此程序要求输入1到12之间的数字,并打印出与输入数字相对应的月份和季节,如果用户键入的不是1到12之间的数字,则会显示错误消息。看起来第一个if语句与其对应的嵌套语句运行得很好,但是下一个if语句不起作用,尝试使用1、2和12,程序将运行得很好,但是它不使用任何其他值,有人知道为什么会发生这种情况吗? 这是程序 #include <iostream> #include <string> using namespace std; int main() { int

此程序要求输入1到12之间的数字,并打印出与输入数字相对应的月份和季节,如果用户键入的不是1到12之间的数字,则会显示错误消息。看起来第一个if语句与其对应的嵌套语句运行得很好,但是下一个if语句不起作用,尝试使用1、2和12,程序将运行得很好,但是它不使用任何其他值,有人知道为什么会发生这种情况吗? 这是程序

#include <iostream>
#include <string>
using namespace  std;

int main() {

  int number;
  string season, month;

  cout << "Welcome! This program will provide the season of the year based on the month you enter, 1 corresponding to January, 2 for February and so on until 12 for December" << endl << endl;

  cout << "Enter a number between 1 and 12: ";
  cin >> number;

  if (number == 1 || 2 || 12)
  {
    if (number == 1)
    {
      month = "January";
      season = "winter";
    }
    else if (number == 2)
    {
      month = "February";
      season = "winter";
    }
    else if (number == 12)
    {
      month = "December";
      season = "winter";
    }
  }
  else if (number == 3 || 4 || 5)
  {
    if (number == 3)
    {
      month = "March";
      season = "spring";
    }
    else if (number == 4)
    {
      month = "April";
      season = "spring";
    }
    else if (number == 5)
    {
      month = "May";
      season = "spring";
    }
  }
  else if (number == 6 || 7 || 8 )
  {
    if (number == 6)
    {
      month = "June";
      season = "summer";
    }
    else if (number == 7)
    {
      month = "July";
      season = "summer";
    }
    else if (number == 8)
    {
      month = "August";
      season = "summer";
    }
  }
  else if (number == 9 || 10 || 11)
  {
    if (number == 9)
    {
      month = "September";
      season = "fall";
    }
    else if (number == 10)
    {
      month = "October";
      season = "fall";
    }
    else if (number == 11)
    {
      month = "November";
      season = "fall";
    }
  }
  else
  {
    cout << "You entered an ivalid value";
    return 0;
  }

  cout << "-------------------------------------------------------------" << endl;
  cout << "You entered " << number << ". " << month << " is the " << season << " season.";
  return 0;
}
#包括
#包括
使用名称空间std;
int main(){
整数;
弦季、弦月;

cout我相信
| |
运算符在使用时不起作用。也就是说,如果(number==1 | | 2 | | 12)
语句很可能被转换为布尔值:

number==1

2

12

所以,想象一下,你是在强迫这些值中的每一个成为一个布尔表示。不过,可能有更确切的方法来解释这一点

修复程序可能会执行以下操作:

if(number==1 | | number==2 | | number==12)


等。

请发布错误消息。