从用户生成的列表中计算最小值和最大值

时间:2017-10-09 01:26:17

标签: c++ loops

我正在编写一个分配代码,要求我创建一个程序,要求用户输入他们想要输入的整数量,然后在测试值是最大值还是最小值时接受每个输入。

程序运行正常,但由于某种原因,当我输入的1个整数小于原始输入时,它会停止并显示最小和最大数字。

我遇到的问题的例子:

  • 如果我为第一个值输入5,它会要求我输入5个整数。
  • 输入4个数字后,1 2 3和4。
  • 它告诉我最大值为4,min为1。
  • 它阻止我输入第5个整数。

此外,

  • 如果我为第一个值输入5,它会要求我输入5个整数。
  • 如果我输入一个负数,如-1,则允许的输入更进一步 缩短。
  • 如果我输入-1,2,3,则输出为min:2且max:3

我有两个主要问题:

  1. 我需要对代码进行哪些调整才能使其正常运行 输入最初要求的整数数量?
  2. 为了让我能够进入需要做出哪些调整 负整数,以便正确输出?
  3. 代码:

    #include <iostream>
    using namespace std;
    
    int main()
    {
        int input;
        int tmp;
        int counter = 1;
        int max_num = 0;
        int min_num;
    
        // prompt user for integer amount
        cout << "How many integers would you like to enter? " << endl;
        cin >> input;
    
        cout << "Please enter " << input << " integers." << endl;
    
        tmp = input;
    
        // loop for requested amount with a test for each input
        while (counter <= tmp) {
            cin >> input;
    
            // if smaller than previous number it is the minimum
            if (input < min_num || min_num == -1) {
                min_num = input;
                counter++;
            }
    
            // if larger than previous number it becomes max number else
            if (input > max_num) {
                max_num = input;
                counter++;
            } else { // continue loop if number isn't bigger than max or smaller than min
                counter++;
            }
        }
    
        // display the max and min
        cout << "min: " << min_num << endl;
        cout << "max: " << max_num << endl;
    
        return 0;
    }
    

0 个答案:

没有答案