我的程序工作正常,但我希望它是完美的。所以我偶然發現了這個問題,當我的函數運行時,它將兩次打印出相同的printf()
語句。程序打印兩次相同的打印語句
讓我告訴你我的意思是,這是我的函數如下(跳過主/原型)
void decision2(struct CardDeck *deck) {
char choice;
int Ess;
printf("\n%s, Your have %d\n", deck->name2, deck->ValueOfSecondPlayer);
while (deck->ValueOfSecondPlayer <= 21)
{
if (deck->ValueOfSecondPlayer == 21) {
printf("You got 21, nice!\n");
break;
}
if (deck->ValueOfSecondPlayer < 21) {
printf("Would you like to hit or stand?\n");
scanf("%c", &choice);
}
if (choice == 'H' || choice == 'h') {
printf("You wish to hit; here's your card\n");
Ess = printCards(deck);
if (Ess == 11 && deck->ValueOfSecondPlayer > 10)
{
Ess = 1;
}
deck->ValueOfSecondPlayer += Ess;
printf("Your total is now %d\n", deck->ValueOfSecondPlayer);
if (deck->ValueOfSecondPlayer > 21) {
printf("Sorry, you lose\n");
}
}
if (choice == 'S' || choice == 's') {
printf("You wished to stay\n");
break;
}
}
}
所以,在我的代碼的東西那怪異這是怎麼組成部分:
if (deck->ValueOfSecondPlayer < 21) {
printf("Would you like to hit or stand?\n");
scanf("%c", &choice);
}
的程序的輸出是變這樣的:
k, Your have 4
Would you like to hit or stand?
Would you like to hit or stand?
h
You wish to hit; here's your card
6 of Clubs
Your total is now 10
Would you like to hit or stand?
Would you like to hit or stand?
h
You wish to hit; here's your card
King of Diamonds
Your total is now 20
Would you like to hit or stand?
Would you like to hit or stand?
s
You wished to stay
正如你所看到的那樣,printf打印了兩次這個語句,並且我無法弄清楚這個程序是否誠實,所以我希望有人確實有解決方案並解釋爲什麼會發生這種情況?
您只使用%c的一個字符,但要輸入它,請按ENTER,這是一個新字符。要麼忽略\ r和\ n,要麼可能使用fgets。 – LSerni