c语言,编写一个猜数字游戏

如题所述

源码如下:

/* File: guess.c */

#include <stdio.h>  /* standard input & output support */

#include <stdlib.h> /* srand() rand() */

#include <time.h>   /* time() */

/* 宏定义 */

#define NUMBER_LENGTH   5   /* 随机数长度 */

#define NUMBER_LIMIT    10  /* 随机数限制, 每一位0-9 */

#define INPUT_LENTH     128 /* 输入缓冲区大小 */

char goal[NUMBER_LENGTH]    = {0};  /* 保存随机数 */

char flag[NUMBER_LIMIT]     = {0};  /* 保存随机数标志, 保证不重复 */

char input[INPUT_LENTH]     = {0};  /* 保存输入 */

/* 初始化用于保存数据的数组 */

void initData()

{

    int i = 0;

    while (i < NUMBER_LENGTH)

        goal[i++] = 0;

    

    i = 0;

    while (i < NUMBER_LIMIT)

    {

        flag[i++] = 0;

    }

}

/* 初始化用于保存缓冲区的数组 */

void initBuffer()

{

    int i = 0;

    while (i < INPUT_LENTH)

        input[i++] = 0;

}

/* 显示猜测结果 */

void display()

{

    int count = 0;

    

    int i = 0;

    while (i < NUMBER_LENGTH)

    {

        if (input[i] == goal[i])

        {

            printf("%c", 'o');

            count++;

        }

        else

        {

            printf("%c", 'x');

        }

        

        i++;

    }

    

    printf("\nRIGHT: %d bit(s)\n", count);

    

    if (count == NUMBER_LENGTH)

    {

        printf("You win! The number is %s.\n", goal);

        

        exit(0);

    }

}

/* 生成随机数 */

void general()

{

    /* 以时间作为时间种子保证生成的随机数真正具有随机性质 */

    srand((unsigned int)time(NULL));

    

    int i = 0;

    while (i < NUMBER_LENGTH)

    {

        char tmp;

        do

        {

            tmp = '0' + ((i != 0) ? (rand() % 10) : (1 + rand() % 9));

        } while (flag[tmp] != 0);

        

        flag[tmp] = 1;

        goal[i++] = tmp;

    }

}

/* 输入方法,用于猜测 */

void guess()

{

    printf("Please input the number you guessed:\n");

    scanf("%s", input);

    display();

    initBuffer();

}

/* 主函数,程序主框架 */

int main (int argc, const char * argv[])

{

    initData();

    initBuffer();

    general();

    while (1) guess();

    return 0;

==============================================

运行结果见附图,希望我的回答能够对你有所帮助。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-08-12
太简单了,给你个编程思路吧:
输入甲猜的数
循环5次,每次都输入一个乙的数,并判断与甲数的关系
如果大则输出你猜的数据大了
如果小则输出你猜的数据小了
如果相同则输出你赢了!游戏结束。并结束程序
如果循环结束都没有猜对,就输出你输了,游戏结束,并输出甲输入的数据
提示:输入用scanf函数
循环可以用for循环
数据可以用整形
第2个回答  2019-05-21
超简单啊。。。。建立3个int对象
要猜的数
猜的数
猜的次数
判断
猜的次数<5
执行
次数++然后让输入
=猜的数
判断猜的数=要猜的
是(输出猜对)否继续执行
判断
猜的数>要猜的(是输出数据大了)否
输出数据小了。。。
相似回答