How to generate a variable with random value in C

Asked

Viewed 262 times

-2

Good night, you guys. Well, I’m taking a C programming course and in this course I have a challenge, to create a game of jokenpô.

I started doing the code part of the game and such and the part that the user chooses which object of the jokenpo will use worked, however I am not able to make a variable receive the random value generated by the function srand.

Sorry for the doubt, guys, I’m starting a little while ago haha I thank you.

  • In the library stdlib.h, use the function random. Rather generate a seed and feed the srandom.

  • If this tip ode question were in scope, it would have several answers already posted before: https://answall.com/questions/tagged/c%2brandom? tab=Votes.

1 answer

0


The program below generates 5 pseudo-random numbers between 1 and 10:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    int num, i;
    srand (time(NULL));
    for (i=1; i<=5; i++) {
        /* gera um número pseudo-aleatório entre 1 e 10 */
        num = rand() % 10 + 1;
        /* faça alguma coisa com o número*/
        printf("%dº número gerado: %d\n", i, num);
    }
    return 0;
}

Note that the srand function generates only the seed of the sequence of random numbers.

  • then basically it is possible to assign the variable the value generated by srand

  • Thanks, I’ll implement this and see if it works

Browser other questions tagged

You are not signed in. Login or sign up in order to post.