猜数字游戏

引入

最近在学习《C语言经典编程282例》,书里有个“猜数字游戏”,虽然很简单,但发现书里还是有些小问题。

猜数字游戏

小时候大家都应该玩过,指定几个数随机产生数字u;猜数字,会提示玩家有几个数字的数字是正确的、位置是正确的或者两者都是正确的。在C里的实现方案可以直接调用数组,与随机产生的数字进行逐个比较,比较的信息为数据本身和位置信息本身,所以总的来讲比较好实现。但是书中代码是基于TC 2.0的IDE开发的,所以一些函数的调用在其他编译器平台就不行了。。。为了解决这个问题,可以自己定义函数来实现一些只有在TC 2.0下的函数

代码

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<conio.h>
#include<dos.h>
#include<windows.h>
void gotoxy(int x, int y) //定位到第y行的第x列
{
    int xx=0x0b;
    HANDLE hOutput;
    COORD loc;
    loc.X = x;
    loc.Y=y;
    hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(hOutput, loc);
    return;
}
main()
{
int i,n;
while(1)
{   system("cls");
    gotoxy(15,6);
    printf("1.start game?(y/n)");
    gotoxy(15,8);
    printf("2.Rule");
    gotoxy(15,10);
    printf("3.exit
");
    gotoxy(25,15);
    printf("Please choose:");
    scanf("%d",&i);
    switch(i)
    {
    case 1:
        system("cls");
        printf("Please input n:
");
        scanf("%d",&n);
        guess(n);
        Sleep(5);
        break;
    case 2:
        system("cls");
        printf("		The Rules Of The Game
");
        printf("step1:input the number of digits
");
        printf("step2:input the number,separated by a space between two numbewrs
");
        printf("step3:A reprsent location and data are correct
");
        printf("	B represent location is correct but data is wrong!
");
        Sleep(7000);
        break;
    case 3:
        exit(0);
    default:
        break;
    }
  }
}
void guess(int n)
{
    int acount,bcount,i,j,k=0,flag,a[10],b[10];
    do
    {
        flag=0;
        srand((unsigned)time(NULL));
        for(i=0;i<n-1;i++)
        {
            for(j=i+1;j<n;j++)
                if(a[i]==a[j])
            {
                flag=1;
                break;
            }
        }
    }while(flag==1);
    do
    {
        k++;
        acount==0;
        bcount=0;
        printf("guess:");
        for(i=0;i<n;i++)
            scanf("%d",&b[i]);
        for(i=0;i<n;i++)
            for(j=0;j<n;j++)
        {
            if(a[i]==b[j])
            {
                acount++;
                break;
            }
            if(a[i]==b[j]&&i!=j)
            {
                bcount++;
                break;
            }
        }
        printf("clue on:%d A %d B 

",acount,bcount);
        if(acount==n)
        {
            if(k==1)
                printf("you are the topmost rung of Fortune's ladder!! 

");
            else if(k<=5)
                printf("you are genius!!

");
            else if(k<=10)
                printf("you are cleaver!!

");
            else
                printf("you need try hard!!

");
            break;
        }
    }while(1);
}

总结

编译环境:CodeBlocks下能正常运行,其中Sleep()命令是在Windows下的休眠函数,与Matlab中的hold on有一点点的类似。。也有sleep()函数,但是大小写sleep函数有些区别,将在下一次更新的时候写写。

作者:YunLambert

-------------------------------------------

个性签名:一名会音乐、爱健身的不合格程序员

可以Follow博主的Github哦(っ•̀ω•́)っ✎⁾⁾

原文地址:https://www.cnblogs.com/yunlambert/p/7568139.html