📜  C中的数字猜谜游戏

📅  最后修改于: 2021-05-28 02:01:43             🧑  作者: Mango

给定整数N。猜数字游戏是一种简单的猜游戏,其中用户应该最多猜10次才能猜出0N之间的数字。尝试10次后,如果玩家未能猜出数字,游戏将结束,然后他将输掉游戏。

例子:

方法:可以按照以下步骤设计游戏:

  • 生成一个介于0N之间的随机数。
  • 然后从1迭代到10,并检查输入的数字是否等于假定的数字。
  • 如果是,则玩家赢得游戏。
  • 否则,尝试10次后终止游戏。

下面是上述方法的实现:

C
// C program for the above approach
#include 
#include 
#include 
  
// Function that generate a number in
// the range [1, N] and checks if the
// generated number is the same as the
// guessed number or not
void guess(int N)
{
    int number, guess, numberofguess = 0;
  
    // Generate a random number
    number = rand() % N;
  
    printf("Guess a number between"
           " 1 and %d\n",
           N);
  
    // Using a do-while loop that will
    // work until user guesses
    // the correct number
    do {
  
        if (numberofguess > 9) {
            printf("\nYou Loose!\n");
            break;
        }
  
        // Input by user
        scanf("%d", &guess);
  
        // When user guesses lower
        // than actual number
        if (guess > number)
  
        {
            printf("Lower number "
                   "please!\n");
            numberofguess++;
        }
  
        // When user guesses higher
        // than actual number
        else if (number > guess)
  
        {
            printf("Higher number"
                   " please!\n");
            numberofguess++;
        }
  
        // Printing number of times
        // user has taken to guess
        // the number
        else
            printf("You guessed the"
                   " number in %d "
                   "attempts!\n",
                   numberofguess);
  
    } while (guess != number);
}
  
// Driver Code
int main()
{
    int N = 100;
  
    // Function call
    guess(N);
  
    return 0;
}


输出:

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。