2015-10-25 48 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

謝謝你的幫助,我試着在網上查找一個解決方案,但並不真正知道如何提出我的問題,我還在學習所有的術語。但是,它的工作,我能夠繼續編碼的程序,非常感謝你! –