2014-04-12 97 views
0

它給了我一個錯誤,說不是所有的控制路徑返回一個值:請幫助。控制路徑不返回值3

int using_range() 
{ 
    int Num; 

    try{ 
     cout << "Please enter a integer between 1 and 10: "; 
     cin >> Num; 
     if ((Num > 10) || (Num < 0)){ 
      throw 77; 
     } 
     else if ((Num <= 10) || (Num >= 0)){ 
      cout << Num << " is in range\n"; 
      return 0; 
      system("pause"); 
     } 
    } 
    catch (int x){ 
     cout << "The number cannot be greater than 10, or less than zero. Error " << x << endl; 
     system("pause"); 
     return 0; 
    } 
} 

林不知道該怎麼辦

+1

只是改變你的'其他if'爲'else' – ryrich

回答

0

的問題是,你有一個if後跟else if,但如果這兩個檢查失敗,沒有什麼默認返回。你的代碼應該防止這種情況發生,但編譯器不夠聰明,無法100%肯定地知道你將永遠不會失敗兩個if檢查。

try{ 
    cout << "Please enter a integer between 1 and 10: "; 
    cin >> Num; 
    if ((Num > 10) || (Num < 0)){ 
     throw 77; 
    } 
    else if ((Num <= 10) || (Num >= 0)){ 
     cout << Num << " is in range\n"; 
     return 0; 
     system("pause"); 
    } 
    // <- if you get here, nothing is going to be returned 
} 

另一種辦法是,改變你的else if只是else

0

所以,只是一個快速的解釋:當你有一個期望有返回值的函數(在你的情況下,int)時,編譯器很高興當你的程序中的全部路徑實際上這樣做。在此代碼中,有可能是一種情況,它可能會通過您的ifelse if,在這種情況下,它不會執行任何操作。如果你願意,你可以在這裏拋出一個錯誤

但我想添加的一件額外的事情是在接收用戶輸入時添加一些保護。也就是說,確保用戶輸入了一個數字!

例如,如果用戶輸入b,輸出將是0 is in range

因此,添加其他檢查,以確保:

int using_range() 
{ 
    int Num; 

    try{ 
     cout << "Please enter a integer between 1 and 10: "; 
     cin >> Num; 

     // this checks if whatever the user input can be parsed as an int. 
     if (!cin){ 
      cout << "please enter a number." << endl; 
      return -1; 
     } 
     else if ((Num > 10) || (Num < 0)){ 
      throw 77; 
     } 
     else if ((Num <= 10) || (Num >= 0)){ 
      cout << Num << " is in range\n"; 
      return 0; 
      system("pause"); // also, this will never happen :) 
     } 
     else{ 
      // not sure how it could get here, but maybe in weird corner cases? 
      return -1; 
     } 
    } 
    catch (int x){ 
     cout << "The number cannot be greater than 10, or less than zero. Error " << x << endl; 
     system("pause"); 
     return 0; 
    } 
} 
相關問題