Need help with a random number game

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?
You need a left-curly brace right after while( x != n ) and a right-curly brace after the right-curly brace after the word "Correct!";
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#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!\n";
        }
        if (x>n)
        {
            cout<<"Thats to high!\n";
        }
        
        cin >> x;
    }

    cout<<"Correct!\n";

    return 0;
}
Last edited on
OK thanks for the quick reply im completely new to c (started today).
You started today and yet you know more then me :D (roughly 6 days) LoL xD
Good luck to both of you!
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/
No problem. Good luck and have fun! :D
Topic archived. No new replies allowed.