I am trying to create a program that compares a set of integers and outputs the min and max value. My code executes correctly for all scenarios except when I have a list of only negative answers to compare. Then the code returns the correct min value and 0 for the max value. Any thoughts?
# include <iostream>
usingnamespace std;
int main ()
{
int numInt, // The total number of integers to be entered
currentInt, // The number of the current integer beig processed
val, // The value of the current integer being processed
minVal, // The integer with the smallest value
maxVal; // The integer with the largest value
// Gets input from the user
cout << "How many integers would you like to enter?\n";
cin >> numInt;
if (numInt == 1)
cout << "Please enter " << numInt << " integer.\n";
else
cout << "Please enter " << numInt << " integers.\n";
// Initializes the loop control variable
currentInt = 1;
// Sets initial min and max values
minVal == val;
maxVal == val;
// Evaluates for minValue and maxValue for each integer
while (currentInt <= numInt)
{
// Compares the value of each entered integer to determine min and max values
cin >> val;
if (val < minVal)
minVal = (val);
if (val > maxVal)
maxVal = (val);
// Sets the loop to the next integer
currentInt = currentInt + 1;
}
// Prints the largest and smallest integers
cout << "min: " << minVal << "\n";
cout << "max: " << maxVal << "\n";
return 0;
}
// Sets initial min and max values
minVal == val;
maxVal == val;
So you need to fix those two lines in two ways:
1) Use '=' not '==' as above
2) There are many ways of getting the ball rolling with starting values for minVal and maxVal and you need to think about them carefully.
minVal should be set at a high enough value so that from knowledge of possible responses from the user all values are guaranteed to be less than that. So pick a big number.
Use the same logic for the initial value for maxVal.