Hey, im relatively new in c++ and im trying to code a Random number guessing game.
Heres the code-
#include <iostream>
#include <ctime> // to use the time function
#include <cstdlib>
using namespace std;
int main()
{
srand(time(0));
int n = rand() % 20;
cout<< "Pick a number 1 through 20: ";
int x;
cin>> x ;
while (x!=n)
if (x<n){
cout<<"Thats to low!";
}
if (x>n){
cout<<"Thats to high!";
}
if (x==n) {
cout<<"Correct!";
}
cin.get();
}
If you've tried this, well it doesn't work, it either loops forever, or doesn't loop at all, so any help?
First; please encapsulate your code with [ code ][ /code ] whenever you post code.
Otherwise, you needed to encapsulate your while loop with parenthesis { }. This was problem number one.
Second problem was that you need to prompt the user to type x again or the while loop will be inifinite.
Thirdly there was a design error in your code. The user wouldn't know if he guessed the right number or not because the while loop terminates before the "cout << "Correct!";
The fourth problem is that you need to return an int from your main.
I've included the corrections made to the code. Use it as a reference to what I was saying above:
#include <iostream>
#include <ctime> // to use the time function
#include <cstdlib>
usingnamespace std;
int main()
{
srand(time(0));
int n = rand() % 20;
cout<< "Pick a number 1 through 20: ";
int x;
cin>> x ;
while (x!=n)
{
if (x<n)
{
cout<<"Thats to low!\n";
}
if (x>n)
{
cout<<"Thats to high!\n";
}
cin >> x;
}
cout<<"Correct!\n";
return 0;
}
Yeah but i have experience coding in python, so i have an advantage :)
Try this site it explains everything in great detail- http://www.cprogramming.com/