最小和最大循环

时间:2017-01-19 05:29:20

标签: c++ loops minmax

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

Intent i=new Intent(Intent.ACTION_PICK);
i.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(i, SELECT_PHONE_NUMBER);

4 个答案:

答案 0 :(得分:0)

if (input < min_num)语句中,min_num的值未定义,因为您没有为min_num分配任何值。您希望#include <climits>并将min_num初始化为INT_MAX

答案 1 :(得分:0)

由于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;
}

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

答案 2 :(得分: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

答案 3 :(得分:0)

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