简体   繁体   中英

Find minimum and maximum values input by the user without using an array

I know in theory that I would, for the maximum, replace the current value with the new integer that the user inputs if it is higher than the latter, and vice versa for the minimum, but I can't how to make this happen with my code. Essentially I am asking if there is a way for me to compare two integers without storing their data.

This is a bit of the code that I have thus far. I have found the average, the amount, and the sum of the integers entered as well as the amount of even and odd integers. I now just need to show the minimum and maximum integer values.

int main()
{
    int intVal;
    int sum = 0;
    int maxValue = -1;
    int minValue = -1;
    double average = 0;
    int count = 0;
    int evenCount = 0;
    int oddCount = 0;

    cout << endl << "Enter an integer (negative value to Quit):  ";
    cin  >> intVal;
    cout << endl;


    while(intVal >= 0)
    {
        count ++;
        sum += intVal;
    
        if(intVal > 0)
            average = sum / count;
    
        if(intVal % 2 == 0)
            evenCount ++;
        else
            oddCount ++;
       
        cout << "Enter an integer (negative value to Quit):  ";
        cin  >> intVal;
        cout << endl;
     }
}

Just compare and update if it should be updated:

if (maxValue < 0 || intVal > maxValue) maxValue = intVal;
if (minValue < 0 || intVal < minValue) minValue = intVal;

detail:

if (                 // if
  maxValue < 0       // there are no value yet (this is the first value)
  ||                 // or
  intVal > maxValue) // new value is larger than current maximum,
  maxValue = intVal; // update the maximum

Here's some code that might help you wrap your head around it

#include <iostream>

using namespace std;

int getmin(int a, int b)
{
  if (a < b)
  {
    return a;
  }
  else
  {
    return b;
  }
}

int getmax(int a, int b)
{
  if (a > b)
  {
    return a;
  }
  else
  {
    return b;
  }
}

int prompt()
{
  int val;
  cout << "Enter an integer (negative to quit): ";
  cin >> val;
  return val;
}

int status(int current, int evens, int odds, int minimum, int maximum, int sum)
{
  cout << "=== Stats (last: " << current << ") ==="
    << "Odds: " << odds << endl
    << "Evens: " << evens << endl
    << "Min: " << minimum << endl
    << "Max: " << maximum << endl
    << "Sum: " << sum << endl
    << "Avg: " << sum * 1.0 / (evens + odds) << endl
    << "Total: " << odds + evens << endl
    << "======" << endl;
}

int main()
{
  int current = 0;
  int evens = 0;
  int odds = 0;
  int sum = 0;
  int minimum = INT32_MAX;
  int maximum = INT32_MIN;

  while (true)
  {
    current = prompt();
    minimum = getmin(minimum, current);
    maximum = getmax(maximum, current);

    if (current < 0)
    {
      break;
    }

    sum += current;

    if (current % 2 == 0)
    {
      evens += 1;
    }
    else
    {
      odds += 1;
    }

    status(current, evens, odds, minimum, maximum, sum);
  }

  cout << "Exiting" << endl;
  return 0;
}

Note that getmin and getmax can be swapped out for the C++ algorithm implementations

Regardless of how you find the minimum and maximum, it is important to always initialize the values to the highest and lowest values that the type can hold, respectively. Otherwise, depending on the range of values entered, your max and min can fail to capture the maximum or minimum values.

Now by choosing to only allow positive numbers and zero, you mitigate against that possibility somewhat, but take your minValue = -1; for example. If you only accept positive numbers as you do, your minValue will never change because the user cannot enter anything less than 0 according to your code.

To initialize the variables to capture the maximum and minimum values, C++ provides std::numeric_limits and in particular the std::numeric_limits::min and std::numeric_limits::max member functions.

To initialize variables to capture the maximum and minimum integer values, you would initialize as follows, eg:

    int min = std::numeric_limits<int>::max(),
        max = std::numeric_limits<int>::min();

With min set to the maximum possible values and max set to the minimum possible value. So no matter what value is entered, there is no possibility of the entered value falling outside of your initialization.

As for looping and finding max and min without storing in an array, etc..., you can do that with a simple ternary as a shorthand if ... else ... , or it is perfectly fine to use a full if ... else ... for each min and max . Using a ternary, you could do:

#include <iostream>
#include <limits>

int main (void) {
    
    int min = std::numeric_limits<int>::max(),
        max = std::numeric_limits<int>::min(),
        n;
    
    while (std::cin >> n && n >= 0) {
        max = n > max ? n : max;
        min = n < min ? n : min;
    }
    
    std::cout << "\nmin: " << min << "\nmax: " << max << '\n';
}

(the code above will break the read-loop upon entry of any value less-than zero)

Example Use/Output

$ ./bin/minmaxlimits
1
9
7
13
2
449
8
-1

min: 1
max: 449

The key here being, don't adjust your max and min initialization values just because you are limiting input to positive values. If you always initialize using the max() and min() numeric limits, you will never go wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM