This program is supposed to accept integer inputs until -99 is input, at which point it's supposed to output the greatest and least values input. But when I run this, it only works if I enter two values or less. Entering "1", "2", "10", and "-99" in that order results in the 10 being assigned to greatest, and 2 to least. I'm sure it's just a simple logic error somewhere, but I cannot find it. Any help would be appreciated.
#include <iostream>
usingnamespace std;
int main()
{
int greatest = -99, least = -99, temp = 0;
while (temp != -99)
{
cout << "Please enter an integer (-99 to end)" << endl;
cin >> temp;
if (greatest == -99)
greatest = temp; //Initial plug-in of values to variables greatest and least.
elseif (least == -99) //This should only happen for the first two input values.
{
least = temp;
if (greatest << least) //Initial test to make sure greatest > least.
{ //If greatest < least, it switches the values.
temp = greatest;
greatest = least;
least = temp;
}
}
elseif (temp >> greatest && temp != -99) //Replaces greatest with temp if greatest < temp.
greatest = temp;
elseif (temp << least && temp != -99) //Replaces least with temp if least > temp.
least = temp;
}
cout << "The largest number you entered was " << greatest
<< ", and the lowest number was " << least << endl;
return 0;
}
#include <iostream>
#include <limits>
usingnamespace std;
int main()
{
// http://www.cplusplus.com/reference/limits/numeric_limits/int greatest = std::numeric_limits<int>::min() ;
int least = std::numeric_limits<int>::max() ;
int temp = 0;
while( cout << "Please enter an integer (-99 to end)\n" &&
cin >> temp && temp != -99 ) // for each number till -99 is entered
{
if( temp /*>>*/ > greatest ) greatest = temp;
if( temp /*<<*/ < least ) least = temp;
}
cout << "The largest number you entered was " << greatest
<< ",\nand the lowest number was " << least << '\n';
}
This small program will, in a loop, read in integers one by one and print them out.
Till std::cin >> number evaluates to false
(That will happen when the input fails; we enter, say abcd when an int is expected.)
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
int main()
{
int number = 0 ;
while( std::cin >> number ) // loop as long as we have read a number
{
std::cout << "you entered " << number << '\n' ;
}
}
This will work like the previous program.
In addition, the loop will be exited if we enter -99 ie. number != -99 evaluates to false.
Finally
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
int main()
{
int number = 0 ;
while( std::cout << "enter a number (-99 to quit): " &&
std::cin >> number && number != -99 )
{
std::cout << "you entered " << number << '\n' ;
}
}