C语言Craps游戏模拟调试:点数阶段重复掷出同点数问题
调试Craps骰子游戏:后续掷骰子结果重复的问题
你的问题根源出在roll_dice函数里的srand调用——每次调用roll_dice都重新初始化随机数生成器,而time(NULL)返回的是秒级时间戳,短时间内多次调用的话,时间戳不会变化,导致每次生成的随机数序列完全一致,自然后续掷骰子的结果和第一次的点数一模一样。
修正方案:
- 将
srand((unsigned) time(NULL))从roll_dice函数中移除,放到main函数的最开头,只执行一次。这样随机数生成器只会初始化一次,后续每次调用rand都会生成不同的随机数。 - 可选:统一游戏内的输出格式,让首次掷骰子和后续的提示保持一致。
修正后的完整代码:
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> int roll_dice(void); bool play_game(void); int main(void) { // 只初始化一次随机数种子 srand((unsigned) time(NULL)); int wins = 0, losses = 0; for(;;) { if(play_game()) { printf("You win!\n"); wins++; } else { printf("You lose!\n"); losses++; } char x; printf("\nPlay again? "); scanf("%c", &x); getchar(); // 吸收输入后的换行符 if(x == 'y' || x == 'Y') continue; if(x == 'n' || x == 'N') { printf("Wins: %d Losses: %d\n", wins, losses); break; } } return 0; } int roll_dice(void) { int die1, die2; die1 = 1 + rand() % 6; die2 = 1 + rand() % 6; return die1 + die2; } bool play_game(void) { int score1 = roll_dice(); if(score1 == 7 || score1 == 11) { printf("You rolled: %d\n", score1); return true; } if(score1 == 2 || score1 == 3 || score1 == 12) { printf("You rolled: %d\n", score1); return false; } else { printf("You rolled: %d\nYour point is %d\n", score1, score1); } for(;;){ int score2 = roll_dice(); if(score2 == 7) { printf("You rolled: %d\n", score2); return false; } if(score2 == score1) { printf("You rolled: %d\n", score2); return true; } else { printf("You rolled: %d\n", score2); } } }
补充说明:
srand的作用是设置随机数生成器的初始种子,只需要在程序启动时执行一次即可。重复调用会重置随机序列,尤其是在同一秒内调用,会导致生成相同的随机数。- 修正后,每次调用
roll_dice都会基于同一个初始种子生成不同的随机数,游戏逻辑就能正常运行了。
内容的提问来源于stack exchange,提问作者tommie997
相关产品推荐
相关产品推荐

