### Keeping track of smallest/largest numbers

I know the answer to this is out there but I'd rather get hints to help me go in the right direction as opposed to just seeing the correct code, I think it will help me learn more. So please don't just give me the answer, if that's possible. I'm very new to C++ so please bear with me.

Using "std_lib_facilities2.h" because I'm working from Stroustrup's book which requires that header (don't ask about the 2).

Here is the problem I'm working on:
Define two variables to keep track of which is the smallest and which is the largest value you have seen so far. Each time through the loop write out the value entered. If itâ€™s the smallest so far, write the smallest so far after the number. If it is the largest so far, write the largest so far after the number.

My problem is that I can't seem to figure out how to initialize the variables to keep track of the smallest and largest numbers. Initializing "smallestNum" with "0" makes it so that in order to output " __ is the smallest number so far" the number must be in the negatives. I have tried initializing the smallest/largest variables to the userInt as well (which seems silly) and that didn't work either.

Currently I'm just focusing on getting the smallestNum variable to work and then I'll figure out the rest from there. (Sorry if this is like the worst written code you've ever seen...)

 ``123456789101112131415161718192021222324252627282930`` `````` #include "std_lib_facilities2.h" int main(){ cout << "Enter one number:" << endl; double userInt = 0.0; while (cin >> userInt){ cout << "You entered " << userInt << endl; double smallestNum = 0.0; double largestNum = userInt; if (userInt < smallestNum){ smallestNum = userInt; cout << smallestNum << " is the smallest number seen so far!" << endl; } else if (userInt > largestNum){ largestNum = userInt; cout << largestNum << "is the largest number seen so far!" << endl; } else{ cout << "Not working." << endl; } } }``````
First, you need to move the definitions of smallestNum and largestNum before the while loop. Right now your code creates these variables each time through the loop, assigning them 0.0 and userInt each time.

Then initialize smallestNum to infinity and intialize largestNum to -infinity. This way, the first time through the loop, userInt will always be less than smallestNum and greater than largestNum.

Putting this together, delete lines 11 & 12, and add this at line 6:
 ``12`` `````` double smallestNum = 1.0/0.0; double largestNum = -1.0/0.0;``````
I get an error when I try that-
error C2124: divide or mod by zero
 ``12345`` ``````#include //... double smallestNum = std::numeric_limits::max(); double largestNum = std::numeric_limits::lowest(); //... ``````
Last edited on
Topic archived. No new replies allowed.