【发布时间】:2020-12-11 00:47:05
【问题描述】:
我想知道为什么我不会得到随机数。我的代码是一个游戏,您可以在其中掷骰子,然后根据您添加的数字或删除 smth。到目前为止有效!现在我想模拟这个游戏 100 次。但在这里我总是得到相同的结果。 我浏览了一些“随机”帖子,我认为我了解 rand 的工作原理,但找不到任何解决方案。 希望你能帮助我。
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int items[] = {10,10,10,10,9};
int roll_dice(){
return rand() % 6;
}
void pick(int index){
if(items[index] > 0){
--items[index];
}
}
bool won(){
return items[0] == 0 && items[1] == 0 && items[2] == 0 && items[3] == 0;
}
bool lost(){
return items[4] == 0;
}
void print_config(){
printf("%u, %u, %u, %u; %u\n", items[0], items[1], items[2], items[3], items[4]);
}
int fullest_basket(){ // Returns index of fullest basket.
int fullest_basket = 0;
int index_basket = 0;
for(int i = 0; i < 4; i++){
if(fullest_basket < items[i]){
fullest_basket = items[i];
index_basket = i;
}
}
return index_basket;
}
void handle_basket(){
for(int i = 0; i < 2; ++i){
int basket = fullest_basket();
if(items[basket] > 0){
--items[basket];
}
}
}
int main(){
srand(time(NULL));
int won_games = 0, lost_games = 0;
for(int i = 0; i < 100; i++){
while(1) {
int rolled = roll_dice(); // return rand() % 6;
if(rolled < 5){
pick(rolled);
} else if( rolled == 5){
handle_basket();
}
if(won()){
won_games++;
//printf("WON!\n");
break;
}
if(lost()){
lost_games++;
//printf("LOST!\n");
break;
}
}
//print_config();
}
printf("%u, %u; %.2f", won_games, lost_games, (float)won_games/(won_games+lost_games));
return 0;
}
【问题讨论】:
-
问题中的源代码缺少
#include <stdio.h>。当我修复它并运行程序时,只要运行间隔超过一秒(time(NULL)的值有足够的时间改变),我就会得到不同的结果。所以这个问题是不可重现的。您可以提交minimal reproducible example。除了实际重现问题之外,它应该是最小的。这意味着您应该将程序剥离到显示非随机行为所需的最少代码量。 -
您没有玩游戏 100 次,您的第二场比赛以第一场比赛的结果开始,并且您不打印第一场比赛的结果。这就是全局变量的问题。
-
啊,我明白了。所以我的 items[] 在第一次调用后实际上是空的。正因为如此,我也赢得了所有其他比赛。所以我只需要填充 items[] 备份或更好地使其成为本地?
-
所以我现在通过在 main 中的 for 循环之后重新填充 items[] 来修复它。
void fill_basket(){ for(int i = 0; i < 4; i++){ items[i] = 10; } items[4] = 9; }
标签: c random random-seed