输入如何存储?

时间:2018-11-01 09:09:37

标签: c++ loops while-loop

我对代码的流向感到困惑,尤其是在输入整数集之后。 例如,如何存储输入,然后比较以在集合中找到最大的输入?

#include <iostream>

using namespace std;

int main()
{
   int n, num, max, k=1;
   cout << " Enter how many integers " << endl;
   cin >> n;

   cout << " enter " << n << " integers: "; // where input be stored
   cin >> max; // this will input the last number right?
   // if i entered 50 55 60 where they will be stored dont i need to store them in in 3 seprate places
   while (k<n)
   { 
      cin >> num; // what is the function of this line? from where the input will be 
      if (num > max)
          max = num;
      k++;
   }
   cout << " largest integer is :" << max << endl;

   return 0;
}

3 个答案:

答案 0 :(得分:1)

让我们逐步完成。 让我们考虑用户选择n >= 1的情况。 (另请注意k = 1)。 我们首先需要用户输入一个数字。

cin >> max;

我们说这个数字是最大值,我们不知道它是否正确,但是我们做这个假设。

然后我们在k < n为真的情况下读取整数。

while (k < n)
{ 
    cin >> num;
    if (num > max)
        max = num;
    k++;
}

因此,我们将一个数字读入num(在while循环外声明的数字)。 然后,如果我们重新分配max等于num,则检查该数字是否大于我们假设第一个数字最大的假设。 然后,我们递增k

我们一直这样做,直到我们读入n个整数为止。 结果max是我们输入的最大数字。

对于存储,我们不需要存储任何内容,在while循环的范围内,我们可以检查数字是否大于max,如果不是,则仅将其与下一个一起丢弃迭代。

答案 1 :(得分:0)

它不存储读取的全部数字。

它将输入的每个新值与当前最大值进行比较。初始最大值设置为读取的第一个数字。

答案 2 :(得分:0)

该程序的问题陈述将类似于:给您n整数。现在,您必须打印所有这些整数中最大的整数。

  • cin >> max将仅接受一个整数作为输入。 max将保留该值。
  • cout << " enter " << n << " integers: ";将在控制台中打印此输出。例如,如果n的值为2,则将打印:enter 2 integers:

查看评论以获取更多详细信息:

#include <iostream>

using namespace std;

int main() {
int n, num, max, k = 1;
cout << " Enter how many integers " << endl; // print
cin >> n; // number of integer to input;

cout << " enter " << n << " integers: ";  // print how many integers to enter as input

cin >> max;  // input for 1st integer, assume it is the maximum integer

// this while loop will take input of the remaining n-1 intergers
// initially k=1, while loop will run until k is less than n
// while loop will run for n-1 times
while (k < n) {
    cin >> num;  // input for 1 integer
    if (num > max) max = num; // if this input integer 'num' is greater than 'max', then update 'max'
    k++; // increment 'k'
}

cout << " largest integer is :" << max << endl; // print the largest integer

return 0;
}