简体   繁体   中英

How to pass rand() values from a function to the main function?

Haven't program for a while, but I have this game project where I need to randomized who will be player 1 and player 2 and I need to use a user-defined function because it will be part of a bigger function. Player 1 and 2 should reflect whaat will be printed above. How can I improve my code? I also cannot use global variables.

#include<stdio.h>

int randomColor(int nRandom, int nRed, int nBlue)
{   
    srand(time(NULL)); 
    nRandom = (rand()%2); 

    switch (nRandom)
    {
        case 0: 
            nRed = 1;
            nBlue = 2;
            printf("\n\n\tPlayer %d = Red\n", nRed);
            printf("\tPlayer %d = Blue\n", nBlue);
            break;
        case 1: 
            nRed = 2;
            nBlue = 1;
            printf("\n\n\tPlayer %d = Blue\n", nRed);
            printf("\tPlayer %d = Red\n", nBlue);
            break; 
    }
}

int main()
{
    int nRandom, nRed, nBlue;
    randomColor(nRandom, nRed, nBlue);
    printf("\nPlayer %d (R) turn", nRed);
    printf("\nPlayer %d (B) turn", nBlue);      
}

Although what you have is fine, you could be more efficient by having one boolean variable instead of the two. Player1Dark=True or False Then Player2Dark is not required, its just !Player1Dark As they are mustually exclusive

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM