【问题标题】:how is the input stored?输入是如何存储的?
【发布时间】:2019-04-05 11:47:36
【问题描述】:

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

#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;
}

【问题讨论】:

    标签: c++ loops while-loop


    【解决方案1】:

    让我们来看看这个。 让我们考虑用户选择n &gt;= 1 的情况。 (另请注意k = 1)。 我们首先需要用户输入一个数字。

    cin >> max;
    

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

    然后我们在k &lt; n 为真时读入整数。

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

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

    我们这样做直到我们读入n 整数。 导致 max 是我们输入的最大数字。

    至于存储,我们不需要存储任何东西,在 while 循环的范围内,我们可以检查数字是否大于最大值,如果不是,我们只需将其丢弃到下一个迭代。

    【讨论】:

    • 我真的非常感谢!花了几个小时试图理解这部分“我们这样做直到我们读入 n 个整数”非常感谢
    • @Sarah_Xx 我希望我能充分涵盖所有内容。
    【解决方案2】:

    它不存储读取的整个数字集。

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

    【讨论】:

      【解决方案3】:

      这个程序的问题陈述如下:给你n整数。现在您必须打印所有这些整数中最大的整数。

      • cin &gt;&gt; max 将只接受一个整数作为输入。 max 将保存该值。
      • cout &lt;&lt; " enter " &lt;&lt; n &lt;&lt; " 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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-15
        • 2017-04-27
        • 1970-01-01
        • 1970-01-01
        • 2021-12-23
        相关资源
        最近更新 更多