Im having trouble with my code. I want to enter a set of integers and find the m
ID: 3585593 • Letter: I
Question
Im having trouble with my code. I want to enter a set of integers and find the min and max number. My code works when I use sets with both positive and negative numbers, but when I use only positive or only negative numbers, my min or max result is zero. For example, if I enter 4 integers - 74, 21, 887, 15. My results will be min:0, max: 887. And if I enter all negative numbers my max will be incorrect. Can you please edit my code or point out what I need to do to fix it? I cannot use arrays.
#include <iostream>
using namespace std;
int main()
{
//Declare variables
int numInt, num, highInt = 0, lowInt = 0;
//Get Number of Intergers to be Entered
cout << "How many integers would you like to enter?" << endl;
cin >> numInt;
//Prompt User to enter all the integers.
cout << "Please enter " << numInt << " integers." << endl;
for (int i = 1; i <= numInt; ++i)
{
cin >> num;
if (num > highInt)
highInt = num;
else if (num < lowInt)
lowInt = num;
}
//Print smallest integer
cout << "lowest number: " << lowInt << endl;
//Print largest integer
cout << "largest: " << highInt << endl;
system("Pause");
return 0;
}
Explanation / Answer
Hi
I have updated the code and highlighted the code chnages below
#include <iostream>
#include <climits>
using namespace std;
int main()
{
//Declare variables
int numInt, num, highInt = INT_MIN, lowInt = INT_MAX;
//Get Number of Intergers to be Entered
cout << "How many integers would you like to enter?" << endl;
cin >> numInt;
//Prompt User to enter all the integers.
cout << "Please enter " << numInt << " integers." << endl;
for (int i = 1; i <= numInt; ++i)
{
cin >> num;
if (num > highInt)
highInt = num;
else if (num < lowInt)
lowInt = num;
}
//Print smallest integer
cout << "lowest number: " << lowInt << endl;
//Print largest integer
cout << "largest: " << highInt << endl;
system("Pause");
return 0;
}
Output: