C中的高或低游戏帮助

时间:2014-09-28 03:51:44

标签: c

我正在尝试制作高或低的游戏。掷三个骰子,加起来,然后猜高或低。当我到达高或低时,我遇到了一些问题。当我运行程序时,它会在我可以回答高或低之前结束。此外,我不知道如何使用while循环继续,直到用户输入错误的猜测。这是我到目前为止所拥有的。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>


int main(void)
{
    srand((unsigned)time(NULL));

    int dice1, dice2, dice3, dicetotal, i; // Variables
    char startGAMEendGame;

    // Initializing variables
    dice1 = 1 + rand() % 6;
    dice2 = 1 + rand() % 6;
    dice3 = 1 + rand() % 6;
    dicetotal = dice1 + dice2 + dice3;

    // Asking the user if they would like to start the game
    printf("\nWould you like to play a game? < Y / N > ");
    scanf("%c", &startGAMEendGame);

    // First If statement to start the game
    if ( startGAMEendGame == 'Y' || startGAMEendGame == 'y')
    {
        int dice1, dice2, dice3, dicetotal, i; // Variables
        char higherOrlower;

        i = dicetotal;                          // Initializing variables
        dice1 = 1 + rand() %6;
        dice2 = 1 + rand() %6;
        dice3 = 1 + rand() %6;
        dicetotal = dice1 + dice2 + dice3;

        printf("\nAwesome. Let's get started with a simple game of higher or lower.\nYou get to guess until you are wrong. \n");

        printf("\nYour first three rolls are %d, %d, %d, and their sum is %d. \n", dice1, dice2,              
        dice3, dicetotal);

        printf("\nWhat is next your guess? Higher or Lower? < H / L > ");
        scanf("%c", &higherOrlower);

        if ( dicetotal > i && higherOrlower == 'H' )
        {
            printf("\nCongratulations! You guessed correctly. ");
        }

        if (dicetotal < i && higherOrlower == 'L')
        {
            printf("\nCongratulations! You guessed correctly. ");
        }
    }

    if (startGAMEendGame == 'N' || startGAMEendGame == 'n')
    {
        printf("\nBummer. Maybe some other time. ");
    }
}

1 个答案:

答案 0 :(得分:1)

在第二个%c中的scanf之前添加空格将解决问题。

这是因为scanf在输入第一个字符后没有使用\n字符。由于Enter键(\n)也是一个字符,它会被scanf("%c",&higherOrlower);消耗掉。 {1}}因此,您的下一个if永远不会被执行,程序结束。%c之前的空格将丢弃所有空格和空格。

相关问题