#c #boolean #void
#c #логическое #пустота
Вопрос:
Я пытаюсь попросить пользователя ввести y или n, и игра либо завершится, либо продолжится. Я также хочу отобразить общий выигрыш и проигрыш, и пользователь выйдет. Может быть, я не получаю реальную комбинацию логических значений и возвращаю данные в функции?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int rollDice(void);
bool playGame(void);
int main(void)
{
srand((unsigned)(time(NULL)));
char userInput;
while (true)
{
playGame();
printf("Would you like to play again?");
scanf("%c", amp;userInput);
if (userInput == 'n' || userInput == 'N')
{
return false;
}
else
{
return true;
}
}
return 0;
}
int rollDice(void)
{
int dice1 = rand()%6 1;
int dice2 = rand()%6 1;
int totaldice = dice1 dice2;
return totaldice;
}
bool playGame(void)
{
int point, total;
int winCounter, looseCounter;
printf("The game is starting!n");
total = rollDice();
printf("You rolled: %dn", total);
if (total == 7 || total == 11)
{
printf("Wow it's your lucky day! You Win!n");
winCounter ;
}
else if (total == 2 || total == 3 || total == 12)
{
printf("Unlucky! You Loose!n");
looseCounter ;
}
else {
point = total;
printf("Your Point is: %dn", point);
while (true)
{
total = rollDice();
printf("You rolled: %dn", total);
if (total == point)
{
printf("You made your point! You Win!n");
winCounter ;
break;
}
else if (total == 7)
{
printf("Thats a %d. You Loose!n", total);
looseCounter ;
break;
}
}
}return true;
}
Комментарии:
1.
scanf("%c", amp;userInput);
—>scanf(" %c", amp;userInput);
2.
int winCounter,looseCounter;
—>int winCounter = 0, looseCounter=0;
3.
return true;
—>//return true;
4. Привет @ LPs, я должен был объявить счетчик выигрышей / проигрышей в main вместо того, чтобы делать это в play func?
5. «проиграть» -> «проиграть».
Ответ №1:
Ваша главная проблема заключается в том, что в случае ввода пользователем чего-то другого 'n'
или 'N'
вы завершаете main с return
помощью инструкции.Удалите его, и цикл может продолжаться.
Лучше, если вы используете логическую переменную для выхода из цикла while:
int main(void)
{
srand((unsigned)(time(NULL)));
char userInput;
bool paygame = true;
while (paygame)
{
playGame();
printf("Would you like to play again?");
scanf(" %c", amp;userInput);
printf ("Test: %cn", userInput);
if (userInput == 'n' || userInput == 'N')
{
paygame = false;
}
}
return 0;
}
Вторая большая проблема — это счетчики функции playgame: они должны быть инициализированы на 0.
int winCounter = 0, looseCounter = 0;
В противном случае отсчет начинается со случайного числа.
Если вы хотите подсчитать все выигрыши и проигрыши во всех сыгранных играх, вы можете просто использовать статические переменные:
bool playGame(void)
{
int point, total;
static int winCounter = 0, looseCounter = 0;
printf("The game is starting!n");
total = rollDice();
printf("You rolled: %dn", total);
if (total == 7 || total == 11)
{
printf("Wow it's your lucky day! You Win!n");
winCounter ;
}
else if (total == 2 || total == 3 || total == 12)
{
printf("Unlucky! You Loose!n");
looseCounter ;
}
else {
point = total;
printf("Your Point is: %dn", point);
while (true)
{
total = rollDice();
printf("You rolled: %dn", total);
if (total == point)
{
printf("You made your point! You Win!n");
winCounter ;
break;
}
else if (total == 7)
{
printf("Thats a %d. You Loose!n", total);
looseCounter ;
break;
}
}
}
printf ("Won: %d - Lose: %dn", winCounter, looseCounter);
return true;
}
Последнее, измените спецификатор scanf
формата " %c"
на, чтобы разрешить scanf
«сбрасывать» 'n'
символ новой строки, оставленный stdin
после каждого ввода пользователем.
Ответ №2:
не используйте return в цикле while. вместо этого используйте переменную и используйте ее для условия. также нет необходимости делать его истинным, поскольку все время условие истинно, пока вы не нажмете n или N
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int rollDice(void);
bool playGame(void);
int main(void)
{
srand((unsigned)(time(NULL)));
char userInput;
bool again = true;
while (again==true)
{
printf("Would you like to play again?");
scanf("%c", amp;userInput);
if (userInput == 'n' || userInput == 'N')
{
again = false;
}
}
return 0;
}
Ответ №3:
Если вы хотите отобразить итоги после выхода пользователя, вам нужно сохранить их вне playGame
функции.
Возвращаемое значение из playGame
на данный момент бессмысленно, поэтому давайте используем его, чтобы указать, выиграл ли игрок:
bool playGame(void)
{
int point, total;
printf("The game is starting!n");
total = rollDice();
printf("You rolled: %dn", total);
if (total == 7 || total == 11)
{
printf("Wow it's your lucky day! You Win!n");
return true;
}
else if (total == 2 || total == 3 || total == 12)
{
printf("Unlucky! You Lose!n");
return false;
}
else
{
point = total;
printf("Your Point is: %dn", point);
while (true)
{
total = rollDice();
printf("You rolled: %dn", total);
if (total == point)
{
printf("You made your point! You Win!n");
return true;
}
else if (total == 7)
{
printf("Thats a %d. You Lose!n", total);
return false;
}
}
}
return false;
}
И небольшая переписка main
:
int main(void)
{
srand((unsigned)(time(NULL)));
int total = 0;
int wins = 0;
char userInput;
while (true)
{
total = 1;
if (playGame())
{
wins = 1;
}
printf("Would you like to play again?");
scanf("%c", amp;userInput);
if (userInput == 'n' || userInput == 'N')
{
break;
}
}
printf("Of %d games, you won %d.", total, wins);
return 0;
}
Комментарии:
1. Привет, @molbdnilo, просто небольшой вопрос. В моем учебнике нам нужно использовать bool (void) . Когда мы возвращаем false в конце функции — что мы на самом деле делаем? я не вижу разницы в возврате false или true в конце функции….