Ayush Chandra
Ayush Chandra

Reputation: 1

Why does my Srand() never chooses 2 when i choose 1?

I created a Game in c of rock, paper & scissors. The problem is whenever i choose 1, my com never ever chooses anything other than 0 and 1. You can simply win the game everytime by choosing 1,2,1 or Rock,paper,rock

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

int com;

int rng(int com)
{

    srand(time(NULL));
    return rand() %com;
}

int Uscore = 0;

int Cscore = 0;

int main()
{

    int i;
    for (i = 1; i <=10; i++)
    {
        int user;
        printf("the computer chose %d\n", rng(2));
        printf("enter 0 for rock \nenter 1 paper \nenter 2 for scissors \n");
        scanf("%d", &user);

        if (com != user)
        {
            if (com == 0 && user == 1 || com == 1 && user == 2 || com == 2 && user == 0)
            {
                Uscore++;
            }
            else
                Cscore++;
        }
        else 
        printf("its a draw\n");
    }
    if (Uscore > Cscore)
    {
        printf("You won");
    }
        else 
        printf("you lost");
    }

strong text

Upvotes: 0

Views: 82

Answers (2)

Yun
Yun

Reputation: 3812

  • srand(time(NULL));: Seeding the pseudo-random number generator only needs to happen once, so only call srand(...) once at the start of the program. Otherwise, calling rng twice within a very short window will result in the same not-so-random number.
  • return rand() %com;: com needs to be 3 to generate a 0, 1, or 2. The modulo operator (%) is basically taking the remainder of a division.
  • The result of rng(2) (which should be rng(3)) is only used for printing. It is never actually written to com. It is better to rename the parameter of the rng function to avoid confusion, and declare com inside the main function.

E.g. modify this part like this:

int user;
int com = rng(3);
printf("the computer chose %d\n", com);

Upvotes: 4

andrew68
andrew68

Reputation: 56

when call rng function, need to pass 3 as parameter not 2. The return value could be 0, 1, 2.

Upvotes: 2

Related Questions