2011-08-04 76 views
2

以前你們都幫過我很多,我回來尋求更多幫助!循環詢問用戶輸入數組

我正在爲學校的另一個C++作業。我必須從用戶那裏收集10到100之間的20個數字,並將它們全部進行比較並打印出不重複的數字。

我堅持的部分是試圖讓用戶輸入循環,直到我有全部20個數字。我對我有意義,但它顯然不工作。對於荒謬的評論感到抱歉,我不得不爲評論評論一切。

任何光線可以灑在我的身上會是驚人的!非常感謝!

int FindDuplicates[20]; // my little array 
int UserInput; // the number from the user to compare 
int count; // the number of numbers entered 

for(count=0; count<FindDuplicates; count++;) // what I am trying to do is have count start at 0. as long as it is less than the max array, add 1 to the count 
{ 
    cout << "Please enter a number between 10 and 100: "; // print out what I would like 
    cin >> UserInput; // get the number from the user 
} 

回答

3

你的問題是如何進入20個有效號碼,是嗎? 我認爲do while while會幫助你。

int FindDuplicates[20]; // my little array 
int UserInput; // the number from the user to compare 
int count = 0; // the number of numbers entered 

do 
{ 
    cout << "Please enter a number between 10 and 100: "; // print out what I would like 
    cin >> UserInput; // get the number from the user 

    if (UserInput >= 10 && UserInput <= 100) 
    count++; 
} while (count < 20); 

希望能幫到你。

+0

非常感謝!現在看來這很容易,我明白了!我只需添加一行,將UserInput添加到由count標記的插槽中的陣列中! – audiedoggie

1

FindDuplicates會給你的指針指向數組(見this),而不是規模。您應該使用

for(count=0; count<20; count++;)

代替。

1

下面一行有語法錯誤,請檢查語句的工作方式。 <FindDuplicates也有問題。確保你明白這個變量的含義。

for(count=0; count<FindDuplicates; count++;)

3
for(int count = 0; count < 20; count++) 
{ 
    cout << "Please enter a number between 10 and 100: "; 
    cin >> userInput; 

    FindDuplicates[ count ] = userInput; 
} 

您還可以檢查有效的輸入有:

while(UserInput < 10 || UserInput > 100) 
{ 
    cout << "Please enter a number between 10 and 100: "; 
    cin >> UserInput; 
} 

如果你只是確保你已經初始化UserInput的東西做的。所以:

int FindDuplicates[ 20 ]; 
int UserInput = 0; 
int count = 0; 

//count has already been defined, so no need to do it again 
for(; count < 20; count++) 
{ 
    //Keep asking until valid input is given 
    while(UserInput < 10 || UserInput > 100) 
    { 
     cout << "Please enter a number between 10 and 100: "; 
     cin >> userInput; 
    } 

    //Add userInput into the array 
    FindDuplicates[ count ] = UserInput; 
}