二分查找和猜数字游戏的实现

二分查找

每次找中间数

在主函数中实现


    #include 
    int main()
    {

        int arr[] = {1,2,3,4,5,6,7,8,9,10};
        int left = 0;
        int right = sizeof(arr)/sizeof(arr[0])-1;
        int key = 7;
        int mid = 0;
        while(left<=right)
        {
            mid = (left+right)/2;
            if(arr[mid]>key)
            {
                right = mid-1;
            }
            else if(arr[mid] < key)
            {
                left = mid+1;
            }
            else
                break;
        }
        if(left <= right)
            printf("找到了,下标是%d\n", mid);
        else
            printf("找不到\n");
    }

猜数字游戏的实现


    #include 
    #include 
    #include 
    #include 
    void menu()
    {
        printf("**************************\n");
        printf("**********1.play**********\n");
        printf("**********0.exit**********\n");
        printf("**************************\n");
    }
    void game()
    {
        int random_num = rand()%100;
        int input = 0;
        while(1)
        {
            printf("请输入一个数:\n");
            scanf("%d",&input);
            if(input > random_num)
            {
                printf("猜大了\n");
            }
            else if(input < random_num)
            {
                printf("猜小了\n");
            }
            else
            {
                printf("恭喜你,猜对了!\n");
                break;
            }
        }
    }
    int main ()
    {
        int input = 0;
        srand((unsigned)time(NULL));
        do
        {
            menu();
            printf("请选择:\n");
            scanf("%d",&input);
            switch (input)
            {
                case 1: game();
                    break;
                case 0: exit;
                    break;
                default:
                    printf("输入错误\n");
                    break;
            }
        }while(input);
        system("color F1");
        return 0;
    }

你可能感兴趣的:(学习)