数字猜谜游戏

数字猜谜游戏

可以使用 for 循环限制用户输入的次数。循环的每次迭代都允许输入一个值。当循环完成指定的重复次数后,就结束循环,不允许再输入数据。下面编写一个简单的程序来演示,这个程序是实现一个数字猜谜游戏。

/* Program 4.7A  A More Interesting Guessing Game */
#include <stdio.h>
#include <stdlib.h>                    /* For rand() and srand() */
#include <time.h>                      /* For time() function    */

int main(void)
{
    int chosen = 0;                     /* 幸运数字                     */
    int guess = 0;                        /* 存储猜测的数字                        */
    int count = 3;                        /* 允许最大的尝试次数            */
    int limit = 20;                     /* 随机值的最大上限 */

    srand(time(NULL));                  /* 使用时间作为随机数的种子     */
    chosen = 1 + rand()%limit;          /* 生成int型随机数从 1 到 limit  作为幸运数字              */

    printf("\n这是一个猜谜游戏.");
    printf("\n请选择一个数从 1 到 20"
           " 这将作为你的幸运数字.\n");

    //从3  2  1
    for( ; count>0 ; --count)
    {
        printf("\n您还有 %d 次机会",count);
        printf("\n请输入猜测数字: ");      /* Prompt for a guess  */
        scanf("%d", &guess);              /* Read in a guess     */

        /* Check for a correct guess */
        if (guess == chosen)
        {
            printf("\n你猜中了!\n");
            return 0;                       /* End the program */
        }

        /* Check for an invalid guess */
        if(guess<1 || guess > 20)
            printf("我说过是从 1 到 20.\n ");
        else
            printf("抱歉. %d 不是幸运数字.\n", guess);
    }
    printf("\n你试了三次都失败了。号码是%ld\n",
           chosen);
    return 0;
}Code language: PHP (php)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注