我对阵列感到非常困惑,而且我有一个关于使用它们的迷你项目,但是我在我的程序中遇到了某个部分并且我没有知道接下来该做什么,有人可以帮忙吗?
问题是:
"编写一个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;
}
答案 0 :(得分:0)
这是你必须要做的事情。您需要使用 FOR 或 WHILE 循环来获取一定数量的用户输入并将其存储在数组中。
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;
答案 1 :(得分: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/)