2014-12-02 58 views
-1

當我談到數組時,我感到非常困惑,而且我有一個關於使用它們的迷你項目,但是我被困在了程序中的某個部分,我不知道下一步該怎麼做任何人都可以幫忙嗎?C++數組程序

的問題是:

「寫一個C++程序從屏幕(由用戶提供)讀5點的整數,並且確定的最大整數,則必須使用一個數組來存儲的5個整數

The following shows a sample output of the program. 

Enter 5 integers: 15 36 -8 92 56 
The largest integer is 92 " 

什麼我已經走到這一步:

#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
int userIntegers[5]; 

cout<<"Enter 5 integers: "; 
cin>>userIntegers[0]; 




//system("pause"); 
return 0; 
} 
+3

閱讀'for'循環。特別是'for(int i = 0; i <5; ++ i)' – 2014-12-02 04:26:15

+0

您可以讀入'userIntegers [0]',但其餘的發生了什麼? – 0x499602D2 2014-12-02 04:29:03

回答

0

這裏是你必須做的事情。您需要使用FORWHILE循環來獲取一定數量的用戶輸入並將它們存儲在數組中。

int userIntegers[5]; 
int largest = 0; 

cout<<"Enter 5 integers: "; 
for (int i=0; i<5; i++) //Use for loop upto how many numbers you need to get as input. 
{ 
    cin>>userIntegers[i];//get the input from user and store it in array at the index 
    /*If the input is the larger than prev largest or For special case to handle if all the values entered is less than zero.*/ 
    if(largest < userIntegers[i] || largest == 0) 
    { 
     largest = userIntegers[i];//Assign the largest number to the variable. 
    } 
} 
cout<<"Largest Integer is: "<<largest; 
0

,或者你可以(使用isstringstrem和INT_MIN)更輕易做到:

int maxnumber = INT_MIN; // for being sure to have at lest one number above 
int number; 
string s; 

cout<<"Enter 5 integers: "; 
cin >> s; 

std::istringstream steam(s); 
while(steam >> number) { 
if (number > maxnumber) { 
    maxnumber = number; 
} 
} 

編輯: 如果你需要一個數組@Sridhar似乎有你的答案(但考慮使用INT_MIN http://www.cplusplus.com/reference/climits/