请教大家一个问题 如图

用C++语言风格实现。有一个三位数的密码锁,已知下面的5个条件。请编程计算它的秘钥。
提示:
(1)可以将每一个条件的判断,写成一个函数,这样程序的结果可能比较清晰。
(2)可以定义一个结构来管理三位数秘钥。
(3)重点:如何将已知的5个条件转换成逻辑表达式。

img

答案:986

就用个整型数组就行了啊,为啥用结构。结构似乎更麻烦......
你可以为每个数字判断是否正确以及位置是否对封装一个函数,然后每个条件就是判断三个数字是否正确和位置是否对的总和就行了

随便写写


class NumberLock {
public:
    NumberLock(int a, int b, int c) : m1(a), m2(b), m3(c){};
    ~NumberLock(){}
    
    // 返回是否有这个数
    bool hasNum(int num) {
        if(m1 == num || m2 == num || m3 == num) {
               return true;
        }
    }
    // 返回是否位置正确, pos从0还是从1开始看自己喜好,注意修改case后的数值
    bool matchNum(int num, int pos) {
        bool ret = false;
        switch(pos) {
            case 0:
                if(num == m1) ret = true;
                break;
            case 1:
                if(num == m2) ret = true;
                break;
            case 2:
                if(num == m3) ret = true;
                break;
            default:
                break;
        }
        return ret;
    }

    bool Match(int a, int b, int c) {
         int hasCnt = 0;
         int matchCnt = 0;
         if(hasNum(a) == true) {
             hasCnt++;
             if(matchNum(a, 0) == true)
                 matchCnt++;
         }
         if(hasNum(b) == true)  {
             hasCnt++;
             if(matchNum(b, 1) == true)
                 matchCnt++;
         }
         if(hasNum(c) == true)  {
             hasCnt++;
             if(matchNum(c, 2) == true)
                 matchCnt++;
         }
         if(hasCnt == 0) {
             cout << "没有一个号码正确" << endl;
         } else {
             cout <<  hasCnt << "个号码正确" << endl;
             if(matchCnt == 0) {
                 cout <<  "位置" << (hasCnt > 1) ? "都" : ""  <<  “不正确” << endl;
             } else if(matchCnt < hasCnt) {
                 cout << (hasCnt - matchCnt) << "个位置不正确" << endl;
             } else {
                 cout << "位置正确" << endl;
             }
         }
    }
protect:
    NumberLock(){};
private:
    int m1;
    int m2;
    int m3;
};