问题描述
该程序要求输入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;
}
解决方法
我相信||
运算符对您的使用方式无效。也就是说,语句if (number == 1 || 2 || 12)
可能会转换为布尔值:
number == 1
2
12
因此,对映像进行成像时,您将强制将每个值转换为布尔表示形式。不过,可能有一种更准确的解释方式。
此修复程序很可能会这样做:
if (number == 1 || number == 2 || number == 12)
等