Is there an issue with my code?

I created this code. It runs as expected, but something seems off.
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    int num1, num2;
    int userGuess;
    srand(time(0));
    int userTries = 0;
    int computerNum;

    cout<<"Please enter 2 integers: ";
    cin>>num1>>num2;
    computerNum = rand() % num1;
    computerNum = rand() % num2;

    cout<<"I'm thinking of a number between " <<num1 <<" and " <<num2<<".\n";

    do
    {

        userTries++;
        cout<<"Enter guess: ";
        cin>>userGuess;
        cout<<" - ";

        if(userGuess < computerNum)
        {
            cout<<"Too Low\n";
        }
        else if(userGuess>computerNum)
        {
            cout<<"Too High\n";
        }
        else if(userGuess == computerNum)
        {

            cout<<"Correct, it took you " <<userTries<<" tries to guess my number.";
        }
    }
    while(userGuess != computerNum);

    return 0;
}



If someone can look at it for me. I would appreciate it thanks.
Last edited on
L27 cin - this displays what has been typed. The last char typed is the cr/lf which is also displayed. Hence the following cout on the next line.
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    int num1, num2;
    int userGuess;
    
    srand(time(0));
    int userTries = 0;
    int computerNum{0};
    
    cout<<"Please enter 2 integers: ";
    cin>>num1>>num2;
    
    computerNum = rand() % (num2 - num1) + num1; // <--
    cout << computerNum << '\n'; // <-- just for testing purposes
    
    cout<<"I'm thinking of a number between " << num1 <<" and " <<num2<<".\n";
    
    do
    {
        
        userTries++;
        cout<<"Enter guess: ";
        cin>>userGuess;
        cout<<" - ";
        
        if(userGuess < computerNum)
        {
            cout<<"Too Low\n";
        }
        else if(userGuess>computerNum)
        {
            cout<<"Too High\n";
        }
        else if(userGuess == computerNum)
        {
            
            cout<<"Correct, it took you " <<userTries<<" tries to guess my number.";
        }
    }
    while(userGuess != computerNum);
    
    return 0;
}



Please enter 2 integers: 15 20
15
I'm thinking of a number between 15 and 20.
Enter guess: 19
 - Too High
Enter guess: 12
 - Too Low
Enter guess: 15
 - Correct, it took you 3 tries to guess my number.Program ended with exit code: 0
Topic archived. No new replies allowed.