C 函数中的printf重复打印,然后停止并正常工作
我正在用C编写一个21点程序,只是因为我被奇怪的错误卡住了 这是代码(很抱歉所有的评论行,我正在努力追踪这个bug): 这是函数deal()中的最后一个printf它在第一个while循环中做了一些加强,它打印这个短语一千次,然后突然停止,它退出函数,执行第二个循环,再次调用函数,打印它必须的所有内容,到达最后一个printf,打印一次,然后停止,一如所愿 所以我不认为while循环有问题,因为它基本上是工作的,只是在printf上停留了一段时间。可能是什么?C 函数中的printf重复打印,然后停止并正常工作,c,pointers,C,Pointers,我正在用C编写一个21点程序,只是因为我被奇怪的错误卡住了 这是代码(很抱歉所有的评论行,我正在努力追踪这个bug): 这是函数deal()中的最后一个printf它在第一个while循环中做了一些加强,它打印这个短语一千次,然后突然停止,它退出函数,执行第二个循环,再次调用函数,打印它必须的所有内容,到达最后一个printf,打印一次,然后停止,一如所愿 所以我不认为while循环有问题,因为它基本上是工作的,只是在printf上停留了一段时间。可能是什么?时间(NULL)返回秒数。 一秒钟之
时间(NULL)
返回秒数。一秒钟之内,
srand(time(NULL))
将获得相同的种子。对于相同的种子,rand将生成相同的随机数列表。
将
srand(time(NULL))
移动到main,这样它只会被调用一次,而不是每次调用deal函数。@YuHao,你说得对,对不起@user3121023:这已经是解决方案了。请考虑把这个作为答案。(当使用相同的种子时,即当时间值相同时,将生成相同的卡。)@user3121023我不敢相信这会起作用。但为什么呢?你能给我解释一下吗?@MOehm,不过这不是问题所在(我想)。它只是一次又一次地打印相同的值,但它在某个点停止了(不知道为什么),并且它按照预期的方式工作。你在每张牌前都播种了它<代码>时间返回特定日期(即纪元)后的秒数。反复生成相同的数字,直到系统时钟提前一秒。因为你只抽了两张牌,第二张牌就会成功。如果你抽十张牌,九秒钟后你会得到很多输出和十张牌。但user3121023在他的回答中已经解释了这一点。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#define NUM_SUITS 4
#define NUM_RANKS 13
void deal(int *pnum_cards, int *prank) {
static bool in_hand[NUM_SUITS][NUM_RANKS] = {false};
const char rank_code[] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K',};
int suit = 0, rank = 0;
srand((unsigned) time(NULL));
suit = rand() % NUM_SUITS;
rank = rand() % NUM_RANKS;
if (!in_hand[suit][rank]) {
in_hand[suit][rank] = true;
*pnum_cards = *pnum_cards - 1;
printf("Pnum_cards In deal %d\n", *pnum_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]);
}
}
// return rank;
// printf("Rank In deal %d\n", rank);
*prank = rank+1;
printf("prank in deal %d\n", *prank);
}
}
int main() {
int t, newcard;
int stay = {false};
int f;
int rank = 0, *prank = &rank;
int totrank = 0, *ptotrank = &totrank;
int num_cards = 2, *pnum_cards = &num_cards;
printf("Prima del while %d\n", *pnum_cards);
printf("Your hand: ");
while (*pnum_cards > 0) {
deal(&num_cards, &rank);
// printf("Nel while: %d\n", *pnum_cards);
//totrank_check(&totrank, &rank);
}
printf("\n");
}
return 0;
}
printf("prank in deal %d\n", *prank);