显示用户输入的数字的最大和最小数字c ++

时间:2017-07-09 03:45:34

标签: c++

# include <iostream>
using std::endl;
using std::cout;
using std::cin;
int main()
{
    int numUserInt;         // Number of integers the user inputs
    int integers;
    int number;
    int maxNumber = 0;
    int minNumber = 0;

    // Get the number of integers
    cout << "How many integers would you like to enter?" << endl;
    cin  >> numUserInt;
    cout << "Please enter " << numUserInt << " integers." << endl;

    integers = 1;

    while (integers <= numUserInt)
    {
        cin >> number;

        if (numUserInt == 1)
            maxNumber = minNumber = number;

        if (number > maxNumber) 
            maxNumber = number;

        if (number < minNumber)
            minNumber = number;

        integers++;
    }

    cout << "min: " << minNumber << endl;
    cout << "max: " << maxNumber << endl;
    return 0;
}

对于家庭作业,我应该问用户&#34;他们想要输入多少个整数&#34;然后在不使用数组的情况下从数量中找到最大值和最小值。在大多数情况下我的程序都有效,但是当用户说出输入-6 -6时,输出是min:-6和max:0。我想要说明最小值和最大值是-6但是我有不知道如何使其余的代码工作。有人知道有办法吗?

2 个答案:

答案 0 :(得分:1)

minmax变量的值设置为初始输入,然后将minmax与用户每次输入的内容进行比较,以检查是否存在需要更新。

答案 1 :(得分:0)

如果您替换了,您的代码将完全按预期工作 if (numUserInt == 1)
通过
if (integers == 1)

这样,来自评论和其他答案的建议,
通过第一次输入初始化最小值和最大值,
实施。

输出:

How many integers would you like to enter?
2
Please enter 2 integers.
-6
-6
min: -6
max: -6