因此,当我输入我想要使用的月份时,例如12月,我将722作为小时,程序会说,"您输入的小时数不能超过一个小时内720"。有办法解决吗?我不想做每个月的if语句,我觉得有一种更简单的方法。这也是我的第一个大学课程
int userPackage, userHours; //Declaring integer variables
double savings, savings2, total; //Declaring double value
string userMonth;
cout<<"\tHello.\nEnter the number of the package you have\n1) Package A\n2) Package B\n3) Package C\n"; //Prompts the user for their package in a menu like fashion
cin>>userPackage; //gets package
if(userPackage > 3 || userPackage < 1) //Error output for numbers that don't match packages
{
cout<<"Error, invalid choice";
return 0;
}
cout<<"Enter the number of hours you have been online."; //Propmts the user for the number of hours they've been online
cin>>userHours; //gets hours
cout<<"Enter the month (by name): ";
cin>>userMonth;
cout<<"\n";
if(userMonth == "January","March","May","July","August","October","December")
{
if (userHours > 744)
{
cout<<"The amount of hours you entered cannot exceed the amount of hours within the month 744";
return 0;
}
}
if(userMonth == "April", "June", "September", "November");
{
if(userHours > 720)
{
cout<<"The amount of hours you entered cannot exceed the amount of hours within the month 720";
return 0;
}
}
if(userMonth == "February");
{
if (userHours > 672)
{
cout<<"The amount of hours you entered cannot exceed the amount of hours within the month 672";
return 0;
}
}
答案 0 :(得分:1)
if(userMonth == "January","March","May","July","August","October","December")
这不符合你的想法(即不比较userMonth
到每个字符串。你可能想要写的语句(它假设你也想要)使用else if
,即使您的代码没有:
if (userMonth == "January" ||
userMonth == "March" ||
userMonth == "July" ||
userMonth == "August" ||
userMonth == "October" ||
userMonth == "December")
{
...
}
else if (userMonth == "April" ||
userMonth == "June" ||
userMonth == "September" ||
userMonth == "November")
{
}
else if (userMonth == "February")
{
}
注意:这些也是区分大小写的比较(即&#34; 1月和#34;不等同于&#34; 1月和#34;或其他任何区别)和将所有东西转换为所有较低或全部上部套管可能更好。
if(userMonth == "April", "June", "September", "November");
// problematic trailing semi-colon ^
结束if
语句,无条件执行下一个块。因此,当输入722
时, 始终 大于720
并且您会收到您正在查看的消息。
{&2;&#34; 2月&#34; if
逻辑中存在同样的错误同样。