首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >最小和最大循环

最小和最大循环
EN

Stack Overflow用户
提问于 2017-01-19 13:29:20
回答 4查看 11.6K关注 0票数 0

我正在为一个赋值编写代码,它希望我编写一个程序,要求用户输入他们想要输入的整数的数量,然后它接受每一个输入,同时测试这个值是最大值还是最小值。我的程序对除1以外的每个整数都运行得很好。当我输入int1时,即使输入的数字在技术上也是最小值,也只记录最大值,这是因为if语句导致循环在找到数字是max还是min时重复,在这种情况下,数字将始终是最大值,因此测试永远不会再次运行。我怎么才能解决这个问题呢?

代码语言:javascript
运行
复制
#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;
}
EN

Stack Overflow用户

回答已采纳

发布于 2017-01-19 14:09:25

代码语言:javascript
运行
复制
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++;
    }
票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41734407

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档