gpt4 book ai didi

c - srand 函数返回相同的值

转载 作者:太空宇宙 更新时间:2023-11-04 05:20:06 25 4
gpt4 key购买 nike

大家好,看看这个程序。

/* The craps game, KN king page 218 */

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

int roll_dice(void);
bool play_game(void);

int roll_dice(void)
{
int roll;

getchar();
srand((unsigned) time(NULL));

roll = rand() % 13;

if(roll == 0)
roll = roll + 1;

return roll;
}

bool play_game()
{
int sum = 0, wins = 0, loss = 0, point;

sum = roll_dice();

printf("You rolled: %d", sum);

if(sum == 7 || sum == 11)
{
printf("\nYou won!\n");
return true;
}

if(sum == 2 || sum == 3 || sum == 12)
{
printf("\nYou lost!!");
return false;
}

point = sum;

printf("\n\nYour point is: %d", point);

do
{
sum = roll_dice();
printf("\nYou rolled: %d", sum);

}while(sum != point);

if(sum == point)
{
printf("\nYou won!!!");
return true;
}

}

int main()
{
char c, wins = 0, losses = 0;
bool check;

do
{
check = play_game();

if(check == true)
wins++;

else if(check == false)
losses++;

printf("\nPlay Again? ");
scanf("%c", &c);

}while(c == 'Y' || c == 'y');

printf("\nWins: %d Losses: %d", wins, losses);

return 0;
}

srand 函数不断返回相同的值 3 或 4 次,是吗?

每次掷骰子时我都想要不同的值,复制代码并运行它看看我的意思

最佳答案

srand() 是一个为 rand() 函数设置种子的函数。您在这里所做的是在您调用的每个 rand() 之前将种子设置为当前时间,如果调用速度足够快,它将为您提供相同的值(因为它将重置为相同的种子,如果足够快,它将是相同的时间值)。

您要做的是在程序启动时(在您的 main() 函数的开头)调用一次 srand()

然后每次你想要一个随机数时调用 rand(),就像你现在正在做的那样,但不是每次都调用 srand()。

关于c - srand 函数返回相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14494375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com