SO i have this code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int x;
x=rand();
int guess;
do{
cout<<"Enter your guess:";
cin>>guess;
if(guess==x)cout<<"You got it ! ;)\n";
else {
cout<<"Wrong(";
if (guess<x) cout<<"too small)\n";
else cout<<"too big)\n";
}
} while (guess != x);
return 0;
}
question: After compiling and running this program, i enter “999999999999” and it keeps repeating the “too big”. why is this so?
additional info: when i set the value of x to constant 10, and i entered 11, i notice it only repeats “too big” once. is there something i am not aware of? or is the code flawed?
many thanks 🙂
If you look at data types, you will see that an
intcan only hold up to 2,147,483,6471. When you try and input a larger number than what your data type can hold thanstd::coutfails and it then tries and process it again in the next loop and that also fails and it sends you in an infinite loop.You can fix your issue by using a bigger data type.
1 – The size of int depends on your machine, please check http://en.cppreference.com/w/cpp/language/types for the list of ranges that an int can hold