2015-10-25 51 views
-1

所以当我输入我想要使用的月份,比如12月,并且我把722作为小时,程序就会说:“你输入的小时数不能超过月内的小时数720“。有没有办法解决?我不想每个月都做一些陈述,我觉得有一个更简单的方法。这也是我第一次上大学的程序这个字符串比较不起作用

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

userMonth ==“一月”,“三月”,“五月”,“七月”,“八月”,“十月”,“十二月”这不是你如何比较字符串与多种可能性。您可以将这些字符串存储在静态常量数组或集合中,并查找该字符串是否在其中。 –

+0

'if(userMonth ==“April”,“June”,“September”,“November”);'我打赌你从来没有在任何书,教程,网站等上看到过这样的if语句。声称是教C++。那么你是怎么想出来的呢? – PaulMcKenzie

回答

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") 
{ 
} 

注:这些也是区分大小写的比较(即“1月”不等同于“1月”或其他任何差异),并且可能会更好地将所有内容转换为全部较低或全部大写。

if(userMonth == "April", "June", "September", "November");
// problematic trailing semi-colon ^

这结束if语句和无条件地执行下一个块。因此,当输入722时,它是总是大于720并且您收到您看到的消息。

在“February”的if逻辑中也有同样的错误。

+0

你的措辞暗示,如果(userMonth ==“January”,“March”,'等于'if(userMonth ==“January”|| userMonth ==“March”|| '它不是。 – Peter

+0

@Peter我明白了你的观点并澄清了我的措词,谢谢 –

+0

谢谢你的帮助,我试着在网上查找一个解决方案,但并不真正知道如何提出我的问题,我还在学习所有的术语。但是,它的工作,我能够继续编码的程序,非常感谢你! –