0

I have written this program to play rock, paper and scissors with the computer. The following generator() is used to generate the computers choice out of rock paper and scissors:

 // Function to generate computer's choice
char generator()
{
    int key= rand();
    int gen = (key % 3)+1;
    char pc;
    // written this print to check what no. random is generating.
    printf("The random function using rand is : %d",key);

    switch (gen)
    {
    case 1:
        pc = 'r';
        break;

    case 2:
        pc = 'p';
        break;

    case 3:
        pc = 's';
        break;
    }

    return pc;
}

Ideally the rand() function should generate a random no. every time. And if I find it's modulus with 3 it should give three possible choices of remainders 0,1,&2. Then I would have assigned a value out of rock, paper and scissors to one out of each value. Then this would be the computer's choice and this would be then matched again the input of the player( Who again enter one choice out of rock, paper and scissors ) and the winner is decided by the usual rules of the game. But the rand() is always generating the number 41. And hence the game is not working properly Can anybody please explain why?

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
Dev Sinha
  • 17
  • 2
  • 1
    Did you initiate with `srand(.)` before? – Damien Dec 16 '21 at 16:20
  • 2
    You need to call [srand()](https://linux.die.net/man/3/rand) with a seed. For example: `srand(time(nullptr));`. – paulsm4 Dec 16 '21 at 16:20
  • 3
    But make sure to call `srand` only once, at the beginning of your program. – Fred Larson Dec 16 '21 at 16:21
  • No I didn't. I simply include the `stdlib.h` header file only. – Dev Sinha Dec 16 '21 at 16:23
  • 2
    See [`srand()` — why call it only once?](https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once/) to amplify on @FredLarson's point. – Jonathan Leffler Dec 16 '21 at 16:23
  • The code shown should not produce the same random number over and over again. However, if there's a bug in the code calling this code (especially if the calling code calls `srand()` more than once), then the behaviour may be explicable. You could also have some sort of fake `rand()` that always returns one less than "The Answer to Life, the Universe, and Everything" (aka 42). – Jonathan Leffler Dec 16 '21 at 16:34

0 Answers0