user2218567
user2218567

Reputation: 94

C++ rand() keeps returning the same number

I can't figure out why my program keeps generating the same random digit for every round. In fact the number won't change unless I quit and restart the program. Since I'm new to C++, this should be a fairly trivial mistake that I don't know about. Below is my code and thanks in advance for your help.

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;

int getRandNum();

int main()
{
    int randNum = getRandNum();

    srand((unsigned int) time(NULL));

.
.
.

}

int getRandNum()
{
    int randNum;

    randNum = rand() % 3 + 1;

    return randNum;
}

Upvotes: 0

Views: 831

Answers (5)

Anatoly Vasilyev
Anatoly Vasilyev

Reputation: 411

Problem in your algorithm, you calling getComputerChoice() only once at the begining of the main(), but you need to do this in your do ... while:

...
if(playQuitOption == 'p' || playQuitOption == 'P')
    {
        cout << endl;

        playerChoice = getPlayerChoice();
        computerChoice = getComputerChoice();
...

Upvotes: 0

AB Bolim
AB Bolim

Reputation: 2115

You just write getComputerChoice() below the getPlayerChoice(), and your issue is resolved.

playerChoice = getPlayerChoice();
computerChoice = getComputerChoice();

Upvotes: 0

u25891
u25891

Reputation: 611

You need to move int computerChoice = getComputerChoice(); to inside the do loop. The code above picks one choice at the start then never picks another.

Upvotes: 0

SomeWittyUsername
SomeWittyUsername

Reputation: 18358

You're calling your computerChoice function only once and use this result for all the subsequent operations.

Also, the call has to be done after seeding the random generator with srand, like was correctly mentioned by @ZdeslavVojkovic

Upvotes: 2

Zdeslav Vojkovic
Zdeslav Vojkovic

Reputation: 14591

You call rand from function getComputerChoice(). However, that function is called before you set the seed with srand.

You need to call srand before the first call of rand function, which also means before getComputerChoice

Upvotes: 2

Related Questions