2017-03-15 59 views
-11

編輯:如何循環的聲明,C++

這裏是工作的,但如果你輸入什麼,但一個數字,程序進入一個無限循環的代碼。

#include <iostream> 

using namespace std; 

int main() 
{ 
    int age; // Declare age as integer 

    do 
    { 
     cout << "Enter Age: "; // Asks the user to enter their age 
     cin >> age; // Takes input as age 
     if (age < 18) // If age is less than 18 
      cout << "Sorry, you cannot use this program" << endl; 
    } while (age < 18); 
    cout << "Welcome"; 

    system("pause"); 
    return 0; 
} 

原貼:

我最近開始學習C++,想知道最好辦法環路Enter Age程序,使用戶能夠重新進入他們的年齡。

#include <iostream> 

using namespace std; 

int main() 
{ 
    int age; // Declare age as integer 

    cout << "Enter Age: "; // Asks the user to enter their age 
    cin >> age; // Takes input as age 

    if (age < 18) // If age is less than 18 
    { 
     cout << "Sorry, you cannot use this program" << endl; 
    } 

    else if (age >= 18) // If age is greater than 18 
    { 
     cout << "Welcome" << endl; 
    } 

    system("pause"); 
    return 0; 
} 
+5

你是什麼意思*最有效*?你肯定不會試圖將人體納入一個循環的納秒? –

+0

「最好」 - 取決於你的意思是「最好的」; 「最有效的」 - 你應該在特定情況下測量每一個。 –

+0

@EdChum謝謝。不,我只想知道什麼效率最高,以便我可以在未來的更大規模的計劃中使用它。 – CypherPsyco

回答

3

高效可能意味着很多東西,但可以肯定,當你寫控制檯(這是在性能方面夠貴的),然後寫爲用戶輸入的東西(這是許多命令並不意味着性能在性能方面更爲昂貴)。

因此,讓我們假設效率意味着打字容易,易於閱讀和易於維護。

do 
{ 
    cout << "Enter Age: "; // Asks the user to enter their age 
    cin >> age; // Takes input as age 
    if (age < 18) // If age is less than 18 
     cout << "Sorry, you cannot use this program" << endl; 
} 
while (age < 18); 
cout << "Welcome" 

如果你想要的東西不那麼容易輸入,閱讀和維護,我建議遞歸。這種方法它的(?只)上漲,它會打動第一學期編程老師:

int GetAge() 
{ 
    int age; 
    cout << "Enter Age: "; // Asks the user to enter their age 
    cin >> age; // Takes input as age 
    if (age >= 18) 
     return age; 
    cout << "Sorry, you cannot use this program" << endl; 
    return GetAge(); 
} 
+0

謝謝,這很好。因此,用戶需要輸入數據的控制檯應用程序很糟糕?這是爲什麼? – CypherPsyco

+0

嘗試輸入「a」。 –

+0

@CypherPsyco「壞」是什麼意思?如果目標是與人互動,不,這不是「壞」 – Caleth

0

進入實際年齡並不需要任何特殊的算法,因爲它不是一個複雜的過程。 簡單的寫:

while (age < 18){ 
cout << "you can't use this program" << endl; 
cin >> age; 
} 

(我不知道你想使用的循環,所以我寫這樣的代碼爲例)

1

要回答你的問題,有沒有一個具體的最好做你的循環的方式,因爲你不能有一個循環在效率和性能和尺寸等方面勝過所有其他循環。您需要選擇一個您想要衡量「最佳」循環的特定參數。

話雖如此,另一種方法是使用遞歸;這將不需要任何while循環。由於沒有規範爲「其中」的循環方式,你使用,這裏是一個不同的替代while循環或do-while循環:

#include <iostream> 
#include <string> 

using namespace std; 

int Age(void) 
{ 
    int age; 

    cout << "Enter Age: "; 
    cin >> age; 

    if (age < 18) 
    { 
     cout << "Sorry, you cannot use this program" << endl; 
     age = Age(); // recursion here when invalid age is entered 
    } 

    else if (age >= 18) 
     cout << "Welcome" << endl; 

    return age; 
} 

int main() 
{ 
    int age = Age(); 
    cout << age << endl; 

    return 0; 
} 

我在這裏做的舉動將代碼轉換爲名爲Age()的單獨函數,然後在int main()中調用該函數。但是,當用戶輸入小於18的年齡時,我也會調用該函數,從而創建一個循環,其中重複調用該函數以重新輸入年齡,直到輸入可接受的值。該值以年齡存儲,然後返回到main()函數。