Thread: Rand() function in another function gives the same value.

  1. #1
    Registered User
    Join Date
    Mar 2019
    Posts
    11

    Rand() function in another function gives the same value.(FIXED)

    So I started to write a Yahtzee game for my assignment and I need to make a function that roles a dice from 1 to 6.When I use the rolladice function that I made It never changes it gives the same number over and over again.How can I fix it.Thanks!
    BTW You can't use Arrays or strings!
    I restart the program to get a different output.
    Example output:
    Player 4 Computer 4
    Player 2 Computer 2
    Player 3 Computer 3 It goes on like this never gives a different result.

    Here is my code.
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include <time.h>
    int rolladice(); /*prototype of the rolladice function*/
    int main()
    {
    printf("Welcome to the Yahtzee game.\n");
    printf("Let's see who is lucky!\n");
    int playerstart,computerstart,start;
    playerstart=rolladice();
    computerstart=rolladice();
    printf("Player:%d - Machine:%d",playerstart,computerstart);
    if(playerstart>computerstart)
        printf("Player is the lucky one,lets get started!");
    else
        printf("Computer is the lucky one,lets get started!");
    
    
    
    
    return 0;
    }
    int rolladice()
    {
    int dice;
    srand(time(0));              /*Using the rand and time functions rolladice function does roll a dice between 1 and 6 */
    dice=1+rand()%6;
    return 1+rand()%6;
    }
    Last edited by kayra09; 04-07-2019 at 07:22 PM.

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    646
    time(NULL) will return the number of seconds after Jan 1st, 1970. You are using the same seed... Put your srand() at the begining of main().

  3. #3
    Registered User
    Join Date
    Mar 2019
    Posts
    11
    It worked!Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Rand function
    By Default99 in forum C Programming
    Replies: 1
    Last Post: 12-29-2017, 05:25 AM
  2. about rand() function.
    By IS La M in forum C Programming
    Replies: 7
    Last Post: 01-17-2016, 06:44 AM
  3. Replies: 2
    Last Post: 11-14-2011, 08:08 AM
  4. Rand() function...
    By Ash1981 in forum C Programming
    Replies: 7
    Last Post: 01-26-2006, 09:04 AM
  5. rand() function
    By jduke44 in forum C Programming
    Replies: 9
    Last Post: 10-07-2005, 05:33 PM

Tags for this Thread