最小和最大循环

Min and Max Loop

我正在为一项作业编写代码,该作业要求我编写一个程序,询问用户他们想要输入的整数数量,然后在测试该值是最大值还是最小值时接受每个输入.对于除 1 之外输入的每个整数,我的程序都运行良好。当我输入 int 1 时,即使输入的数字在技术上也是最小值,但仅记录最大值,这是由于 if 语句导致循环一旦找到就重复out 如果数字是最大值或最小值,在这种情况下,数字将始终是最大值,因此测试永远不会再次运行。我怎样才能解决这个问题?

#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 = input;
            counter++;
        }

// if larger than previous number it becomes max number
        else if (input > max_num){
            max_num = input;
            counter++;
        }


//continue loop if number isn't bigger than max or smaller than min
        else {
           counter++;
        }



    }

//display the max and min
    cout << "min: "<< min_num << endl;
    cout << "max: " << max_num<< endl;;



    return 0;
}

在语句 if (input < min_num) 中,min_num 的值未定义,因为您没有为 min_num 赋值。您想要 #include <climits> 并将 min_num 初始化为 INT_MAX

问题的出现是因为 int min_num 的默认值为 0,因为 min_num 是一个全局变量。在 while 循环之前添加这行代码,它应该可以正常工作。

if(input >= 1)
    cin >> min_num;
tmp = input-1;
if((input==1)&&(min_num > max_num)){
    max_num = min_num;
    min_num = 0;
}

如果只加一个整数则结果相反。所以我们需要错误检查。顺便代码不好

试试这个代码

#include <iostream>
#include <limits>
using namespace std;

int main() {
    int n, input, max_num, min_num;
    max_num = numeric_limits<int>::min();
    min_num = numeric_limits<int>::max();
    cin >> n;
    while (n--) {
        cin >> input;
        max_num = max(max_num, input);
        min_num = min(min_num, input);
    }
    cout << "min: " << min_num << "\nmax: " << max_num << endl;
    return 0;
}

输入

2
34
65

输出

min: 34
max: 65
int max_num = -1;
int min_num = -1
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++; => This operation is carried out in every case. Why not just do it once?
        }

// if larger than previous number it becomes max number
// Else statement not needed here, What if user inputs only one number. It will be both max and min
        if (input > max_num){
            max_num = input;
            //counter++;
        }

//continue loop if number isn't bigger than max or smaller than min
           counter++;
    }