rand()在第一次之后返回相同的值

首先,这是我的代码:

#include  #include  #include  #include  #define NUM_SUITS 4 #define NUM_RANKS 13 bool in_hand[NUM_SUITS][NUM_RANKS] = {false}; bool newcard = {false}; int num_cards, rank, suit, totrank; const char rank_code[] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K',}; const char suit_code[] = {'C','D','H','S'}; int main_hand () { suit = rand() % NUM_SUITS; rank = rand() % NUM_RANKS; if (!in_hand[suit][rank]) { in_hand[suit][rank] = true; num_cards--; if (suit == 0){ printf("%c of Clubs \n", rank_code[rank]); } else if (suit == 1){ printf("%c of Diamonds \n", rank_code[rank]); } else if (suit == 2){ printf("%c of Hearts \n", rank_code[rank]); } else if (suit == 3){ printf("%c of Spades \n", rank_code[rank]); } } } int print_hand (suit) { } int totrank_check (totrank) { if (totrank > 21) { printf ("You lose!"); } else if (totrank == 21) { printf ("You win!"); } } int main() { bool stay = {false}; srand((unsigned) time(NULL)); totrank = 0; num_cards = 2; printf("Your hand: "); while (num_cards > 0) { main_hand(); totrank = totrank + (rank + 1); } printf("Total rank: %d\n", totrank); totrank_check(totrank); printf("\n"); while (totrank < 24 && stay == false) { printf("Another card? 1. Yes 0. No\n"); scanf("%d", &newcard); if(!newcard) { main_hand(); } totrank = totrank + (rank + 1); totrank_check(totrank); printf("Total rank: %d\n", totrank); printf("Stay? 1. Yes 0. No\n"); scanf("%d", &stay); } return 0; } 

基本上它是一个“模拟”和二十一点手的代码。 它开始, rand()选择两个数字,卡的等级和套装,在矩阵中设置为true,这样就不能再在同一组合中选择它们然后打印。 检查卡的总排名(如果它超过21你会自动丢失)然后会询问你是否想要另一张卡或者你想留下。

这是错误:如果您选择想要其他卡,这张新卡将与最后一张卡相同。 基本上,你得到一个黑桃王牌,两个钻石,然后你想要另一张牌,你得到另外两个钻石。 而另一个,另一个。 如果您在第二个中删除排名检查,而您可以看到排名根据最后一张卡的排名增长。

之前,printfs在print_hand()函数中,你可以看到你总是得到相同的卡,现在我在main_hand()函数中移动它们,因为我认为它可能是问题(它不是)和因为具有单独的打印function是多余的。 但是从技术上来说,你可以看到if(!in_hand[suit][rank])有效,因为,由于卡片是相同的,它不会输入if而且它不会被打印出来。

我不知道是什么导致了这个问题。 任何的想法?

请注意我已经在使用srand((unsigned) time(NULL)); 种子rand()

scanf("%d", &newcard);scanf("%d", &stay); 是一个问题,因为变量是bool ,但格式说明符是int 。 在2个地方,改变如下:

 // scanf("%d", &newcard); int t; scanf("%d", &t); newcard = !!t; 

3个函数返回int但不返回任何内容。 更改为无效function。

 // int main_hand() { void main_hand() { 

似乎还有其他逻辑问题。
1)代码有时存在而不知道是否赢了
2)@Jongware评论以上正确:

最后:如果仍然出现相同的随机序列,则将代码剥离到裸main srand time printf rand并查看是否有效。 time() ,如果不工作,则总是返回-1。
或者简单地添加以下内容并validation使用不同值调用的srand()

  int main(void) { unsigned now = (unsigned) time(NULL); printf("now = %u\n", now); srand(now);