猜数字

#include 
#include 
#include 
#include 

int main(int argc, const char * argv[]) {
    /*
     4位数 从小到大  没有重复 1-9
     A 表示存在而且位置也对的个数 
     B 表示存在但是位置不对
     1 2 3 4
     1 4 6 8
     1A1B
     */
    int array[4] = {};
    bool isExist = false;
    
    //设置随机数的种子
    srand((unsigned int)time(NULL));
    for (int i = 0; i < 4; i++) {
        int temp = rand() % 9 + 1;//1-9

        //判断是否存在
        for (int j = 0; j < i; j++) {
            if (array[j] == temp) {
                //已经存在了
                //把这次机会还给我
                i--;
                
                isExist = true;
            }
        }
        
        //判断是否应该保存这个数字
        if (isExist == false){
            //保存
            array[i] = temp;
        } else{
            //存在了
            isExist = false;
        }
        
    }
    
    //冒泡排序
    int temp;
    for (int i = 0; i < 4; i++){
        for (int j = 4-1-1; j >= i; j--) {
            if (array[j] > array[j+1]) {
                temp = array[j];
                array[j] = array[j+1];
                array[j+1] = temp;
            }
        }
    }
    // 6 7 9
    
//    for (int i = 0; i < 4; i++){
//        printf("%d ", array[i]);
//    }
    printf("\n");
    
    //接收用户的输入
    int totalWrongTime = 10;
    int wrongTime = 0;
    int inputedArray[4] = {};
    int countA = 0;
    int countB = 0;
    
    do {
        printf("请输入数字:");
        for (int i = 0; i < 4; i++) {
            scanf("%d", &inputedArray[i]);
        }
        
        //判断用户的输入结果
        for (int i = 0; i < 4; i++){
            for (int j = 0; j < 4; j++) {
                if (array[i] == inputedArray[j]) {
                    //数字存在了
                    //判断位置是否相同
                    if (i == j){
                        //位置也相同
                        countA ++;
                    } else{
                        //位置不同
                        countB ++;
                    }
                }
            }
        }
        
        //对结果进行处理
        if (countA == 4){
            printf("Congratulation to you !\n");
            break;
        } else{
            printf("%dA%dB\n", countA, countB);
            
            wrongTime ++;
            
            //对结果清零
            countA = 0;
            countB = 0;
        }
    } while (wrongTime < totalWrongTime);
    
    return 0;
}

你可能感兴趣的:(猜数字)