Reputation: 2269
I am trying to find the minimum and maximum value. I am running into following two issues:
Any tips would be appreciated.
#include <iostream>
using namespace std;
int main()
{
int input;
int max = 0;
int min = 0;
cout << "Enter number: ";
while (input != -1)
{
cin >> input;
if(input != -1)
{
if(input > max)
{
max = input;
}
if(input < min)
{
min = input;
}
}
}
cout <<"Max: " << max << " Min " << min << endl;
}
Upvotes: 0
Views: 24987
Reputation: 689
At the beginning, instead of setting to 0, ask for the first number before the while loop and set min and max to that number. As a side note, using -1 as a quit condition for something which accepts numerical input might lead to problems, you might want to ask them for the number of numbers beforehand or detect non numerical input to end the program.
EDIT: example code:
int main(int argc, char** argv)
{
int input;
bool hasInput = false;
cout << "Enter number: ";
cin >> input;
int max = input;
int min = input;
cout << "Enter number: ";
while (cin >> input)
{
if(input == -1) break;
hasInput = true;
if(input > max)
{
max = input;
}
if(input < min)
{
min = input;
}
cout << "Enter number: ";
}
if(hasInput)
cout <<"Max: " << max << " Min " << min << endl;
}
Forgot to check if the first input is -1... im sure you can figure that one out.
Upvotes: 1
Reputation: 11197
From your code I guessed that there will be no negative number. Then do something like this:
EDIT:This part from another answer will be good.
include <iostream>
using namespace std;
int main()
{
int input;
int hasInput = 0;
int max = std::numeric_limits<int>::min();
int min = std::numeric_limits<int>::max(); //#include <limits>
cout << "Enter number: ";
while (cin >> input)
{
if(input == -1) break;
hasInput = 1;
if(input > max)
{
max = input;
}
if(input < min)
{
min = input;
}
}
if(hasInput == 1)
cout <<"Max: " << max << " Min " << min << endl;
}
Upvotes: 3
Reputation: 8805
Just like @Turix said, the problem is because of your initial max
and min
values. Your max
value should be the smallest possible integer value so that anything is greater than it, similarly your min
should be the largest possible integer value. With this in hand, intialize your variables like this:
int max = std::numeric_limits<int>::min();
int min = std::numeric_limits<int>::max(); //#include <limits>
Upvotes: 1