You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++猜数字游戏:数组去重与结果匹配逻辑实现求助

C++猜数字游戏:去重与结果反馈实现方案

问题背景

本人是编程新手,要实现一款C++猜数字游戏,需求如下:

  • 生成包含5个1-9无重复数字的数组
  • 接收用户逐位输入的5位猜测数组,按规则输出反馈:
    • *:数字位置完全正确
    • +:数字存在但位置错误
    • -:无此数字
  • 重复流程直到用户全猜对

目前已完成部分代码,但卡在**数组去重(Step4)和结果匹配反馈(Step7)**的实现,附上现有代码寻求帮助。

原代码:

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void game_instructions(int n);
bool search_array(int a[], int n, int t);
int main()
{

    //Step 1: Declare your variables and constants
    const int SIZE = 5; //this constant stores the length/size of the code

    int randcode[SIZE]; //this array stores the code generated randomly by the computer
    int guess[SIZE];    //this array stores the code inputted by the player/user
    
    //you may add more variables as needed
  
    //Step 2: Output game instructions by calling function game_instructions
    game_instructions(SIZE);
    //Step 3: Generate a random code and store it in the array randcode one digit at a time.
    //Each digit should be between 0 and 9 and should be stored as one array element
    //Recall that rand() % 10 can be used to generate a number between 0 and 9
    srand(time(0));
    for(int i=0;i<SIZE;i++)
       randcode[i]= (rand() % 10);  //Computers random 5 numbers generated
    
    cout<<"\nRandom C-numbers::"<<endl;
    
    for(int i=0;i<SIZE;i++)
       cout<<randcode[i] << " ";
    
    //Step 4: Repeat step 3 if the array randcode contains duplicates
    //You must use function contains_duplicates to implement this step
    
    
    
    //Step 5: Ask the user for his guess and store it in the array guess.
    //Read one digit at a time, validate it to make sure it is between 0 and 9, and store it as one array element
       
    for (int i=0; i<SIZE; i++) {
        cout<<"\nEnter Digit "<< i+1 << ": ";
        cin >> guess[i];}
            
    cout << endl;
    //Step 6: Output the array guess on a single line with a space after each element (see the sample output provided)
    for (int n=0; n < SIZE; ++n) {
        cout << guess[n] << "  ";
    }
    //Step 7: Compare the randomly generated code (randcode) with the user's guess (guess)
    //and display feedback for each digit as: *, + or –, as explained below:
    //For each digit in the user's guess do the following:
        // If it matches the digit from the random code (both value and position), output *
        // Otherwise, if it appears anywhere in the random code, output + (use function search_array here)
        // Otherwise, output -
        
    //Step 8: Repeat steps 5,6,7 until all digits have been guessed correctly
    
    //Step 9: Output congratulations message
    cout << endl << endl;
    cout << "Good job! You guessed the code!";
    return 0;
}

void game_instructions(int n)
//This function outputs the game instructions.
//Its parameter n represents the length of the code.
{
    cout << "A random " << n << " digit code has been generated. You have to guess it. \n";
    cout << "For every digit you will receive feedback in the form of *, + or -  \n";
    cout << "   * means the digit is in the code and it is in the correct position.\n";
    cout << "   + means the digit is in the code but it is not in the correct position.\n";
    cout << "   - means the digit is not in the code.\n";
}


bool search_array(int a[], int n, int t)
//This function searches the array a (of size n) for a target value t.
//If t is found in the array the function returns true; otherwise it returns false.
{
    for (int i = 0; i < n; i++)
    {
        if (a[i] == t) return true;
    }
    return false;
}

bool contains_duplicates(int a[], int n)
//This function searches the array a (of size n) and returns true if the array contains duplicates; otherwise, it returns false.
{
    for (int i = 0; i < n; i++)
    {
        //compare element a[i] with all the remaining elements from index i+1 to n
        for (int j = i+1; j < n; j++)
        {
            if (a[i] == a[j]) return true;
        }
    }
    return false;
}

解决方案

1. 修复随机数范围(符合1-9要求)

原代码生成0-9的数字,需改为rand() % 9 + 1生成1-9的随机数,同时结合去重逻辑确保无重复。

2. Step4:实现数组去重

利用已编写的contains_duplicates函数,用do-while循环重复生成数组,直到数组无重复元素:

// Step3 + Step4: 生成无重复的1-9随机数组
do {
    for(int i=0;i<SIZE;i++) {
        randcode[i] = rand() % 9 + 1; // 生成1-9的数字
    }
} while(contains_duplicates(randcode, SIZE)); // 有重复则重新生成

3. Step7:实现结果匹配反馈

直接按规则判断会出现重复计数问题(如随机数组中某数字仅出现一次,但用户猜两次会错误输出两个+),需分两步处理:

  • 先标记所有位置完全匹配的数字(*)
  • 对剩余数字,检查是否存在于随机数组中,同时跳过已匹配的数字避免重复统计

实现代码:

// Step7: 生成反馈
bool used_rand[SIZE] = {false}; // 标记随机数组中已匹配的位置
bool used_guess[SIZE] = {false}; // 标记猜测数组中已匹配的位置
char feedback[SIZE];
bool correct = true;

// 第一步:处理位置正确的*
for(int i=0; i<SIZE; i++) {
    if(guess[i] == randcode[i]) {
        feedback[i] = '*';
        used_rand[i] = true;
        used_guess[i] = true;
    } else {
        correct = false;
        feedback[i] = ' '; // 占位待后续处理
    }
}

// 第二步:处理+和-
for(int i=0; i<SIZE; i++) {
    if(used_guess[i]) continue; // 跳过已匹配的*
    
    bool found = false;
    for(int j=0; j<SIZE; j++) {
        if(!used_rand[j] && guess[i] == randcode[j]) {
            feedback[i] = '+';
            used_rand[j] = true;
            found = true;
            break;
        }
    }
    if(!found) {
        feedback[i] = '-';
    }
}

// 输出反馈
cout << "\nFeedback: ";
for(int i=0; i<SIZE; i++) {
    cout << feedback[i] << " ";
}

4. Step8:实现循环猜数直到全对

将Step5、6、7的代码放入while循环,直到用户完全猜对:

// Step8: 循环猜数直到全对
do {
    correct = true;
    // Step5: 接收用户输入并验证
    for (int i=0; i<SIZE; i++) {
        do {
            cout<<"\nEnter Digit "<< i+1 << " (1-9): ";
            cin >> guess[i];
            if(guess[i] <1 || guess[i]>9) {
                cout << "Invalid input! Please enter a number between 1 and 9." << endl;
            }
        } while(guess[i] <1 || guess[i]>9);
    }
        
    // Step6: 输出用户猜测
    cout << "\nYour guess: ";
    for (int n=0; n < SIZE; ++n) {
        cout << guess[n] << "  ";
    }

    // Step7: 生成反馈(上述反馈代码)
    bool used_rand[SIZE] = {false};
    bool used_guess[SIZE] = {false};
    char feedback[SIZE];

    for(int i=0; i<SIZE; i++) {
        if(guess[i] == randcode[i]) {
            feedback[i] = '*';
            used_rand[i] = true;
            used_guess[i] = true;
        } else {
            correct = false;
            feedback[i] = ' ';
        }
    }

    for(int i=0; i<SIZE; i++) {
        if(used_guess[i]) continue;
        
        bool found = false;
        for(int j=0; j<SIZE; j++) {
            if(!used_rand[j] && guess[i] == randcode[j]) {
                feedback[i] = '+';
                used_rand[j] = true;
                found = true;
                break;
            }
        }
        if(!found) {
            feedback[i] = '-';
        }
    }

    cout << "\nFeedback: ";
    for(int i=0; i<SIZE; i++) {
        cout << feedback[i] << " ";
    }
    cout << endl;

} while(!correct);

修改后的完整代码

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

void game_instructions(int n);
bool search_array(int a[], int n, int t);
bool contains_duplicates(int a[], int n);

int main()
{
    const int SIZE = 5;
    int randcode[SIZE];
    int guess[SIZE];
    
    game_instructions(SIZE);
    
    // 初始化随机种子
    srand(time(0));
    
    // Step3 + Step4: 生成无重复的1-9随机数组
    do {
        for(int i=0;i<SIZE;i++) {
            randcode[i] = rand() % 9 + 1; // 生成1-9的数字
        }
    } while(contains_duplicates(randcode, SIZE));

    // 可选:调试用,发布时可注释
    cout<<"\n[Debug] Random Code::"<<endl;
    for(int i=0;i<SIZE;i++) {
       cout<<randcode[i] << " ";
    }
    
    // Step8: 循环猜数直到全对
    bool correct = false;
    do {
        correct = true;
        // Step5: 接收用户输入并验证
        for (int i=0; i<SIZE; i++) {
            do {
                cout<<"\nEnter Digit "<< i+1 << " (1-9): ";
                cin >> guess[i];
                if(guess[i] <1 || guess[i]>9) {
                    cout << "Invalid input! Please enter a number between 1 and 9." << endl;
                }
            } while(guess[i] <1 || guess[i]>9);
        }
            
        // Step6: 输出用户猜测
        cout << "\nYour guess: ";
        for (int n=0; n < SIZE; ++n) {
            cout << guess[n] << "  ";
        }

        // Step7: 生成反馈
        bool used_rand[SIZE] = {false};
        bool used_guess[SIZE] = {false};
        char feedback[SIZE];

        // 先处理位置正确的*
        for(int i=0; i<SIZE; i++) {
            if(guess[i] == randcode[i]) {
                feedback[i] = '*';
                used_rand[i] = true;
                used_guess[i] = true;
            } else {
                correct = false;
                feedback[i] = ' ';
            }
        }

        // 处理+和-
        for(int i=0; i<SIZE; i++) {
            if(used_guess[i]) continue;
            
            bool found = false;
            for(int j=0; j<SIZE; j++) {
                if(!used_rand[j] && guess[i] == randcode[j]) {
                    feedback[i] = '+';
                    used_rand[j] = true;
                    found = true;
                    break;
                }
            }
            if(!found) {
                feedback[i] = '-';
            }
        }

        // 输出反馈
        cout << "\nFeedback: ";
        for(int i=0; i<SIZE; i++) {
            cout << feedback[i] << " ";
        }
        cout << endl;

    } while(!correct);
    
    // Step9: 输出祝贺信息
    cout << endl << endl;
    cout << "Good job! You guessed the code!";
    return 0;
}

void game_instructions(int n)
{
    cout << "A random " << n << " digit code (1-9, no repeats) has been generated. You have to guess it. \n";
    cout << "For every digit you will receive feedback in the form of *, + or -  \n";
    cout << "   * means the digit is in the code and it is in the correct position.\n";
    cout << "   + means the digit is in the code but it is not in the correct position.\n";
    cout << "   - means the digit is not in the code.\n";
}

bool search_array(int a[], int n, int t)
{
    for (int i = 0; i < n; i++)
    {
        if (a[i] == t) return true;
    }
    return false;
}

bool contains_duplicates(int a[], int n)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = i+1; j < n; j++)
        {
            if (a[i] == a[j]) return true;
        }
    }
    return false;
}

关键说明

  • 修正随机数范围为1-9,匹配需求
  • 用do-while循环结合contains_duplicates确保数组无重复
  • 反馈生成通过标记数组避免重复计数,保证反馈准确
  • 增加用户输入验证,确保输入为1-9的有效数字
  • 实现循环猜数逻辑,直到用户完全猜对

内容的提问来源于stack exchange,提问作者Slinx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 22:01:09