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

Vector与for循环无输出结果:石头剪刀布游戏开发问题

解决石头剪刀布游戏中基于另一个Vector填充元素的问题

嘿,我看你在开发石头剪刀布小游戏的时候,卡在了用另一个vector的元素作为条件来填充新vector这一步,结合你贴出来的代码片段,我来帮你梳理下可行的解决思路和具体实现~

先把你给出的代码片段完整展示下(补全了showVect的基础实现,方便后续演示):

#include "stdafx.h"
#include "../../Library/std_lib_facilities.h"

// 借助斐波那契数列生成秘密数字序列
int fib(int n){
    if (1 == n || 2 == n) {
        return 1;
    } else {
        return fib(n - 1) + fib(n - 2);
    }
}

// 展示给定vector中的元素列表
void showVect(const vector<string>& v) {
    for (const auto& elem : v) {
        cout << elem << " ";
    }
    cout << endl;
}

核心思路拆解

我猜你的需求大概是:先通过斐波那契生成一串秘密数字序列,然后根据这串数字的某种规则(比如取模结果、数值大小等),映射成石头/剪刀/布的手势,填充到游戏用的vector里?如果是这样的话,核心步骤就是:

  1. 先生成完整的斐波那契秘密序列vector
  2. 遍历这个序列的每个元素,根据你设定的条件判断,往目标vector里添加对应的手势

完整实现示例

下面是一个可运行的完整版本,你可以参考修改:

#include "stdafx.h"
#include "../../Library/std_lib_facilities.h"

// 借助斐波那契数列生成秘密数字序列
int fib(int n){
    if (1 == n || 2 == n) {
        return 1;
    } else {
        return fib(n - 1) + fib(n - 2);
    }
}

// 展示给定vector中的元素列表
void showVect(const vector<string>& v) {
    for (const auto& elem : v) {
        cout << elem << " ";
    }
    cout << endl;
}

int main() {
    // 第一步:生成前10个斐波那契数的秘密序列
    vector<int> secret_seq;
    for (int i = 1; i <= 10; ++i) {
        secret_seq.push_back(fib(i));
    }

    // 第二步:根据秘密序列的元素条件,填充游戏手势vector
    vector<string> game_gestures;
    for (int num : secret_seq) {
        // 这里用斐波那契数模3的结果作为映射条件,你可以改成自己的规则
        switch (num % 3) {
            case 0:
                game_gestures.push_back("rock");     // 石头
                break;
            case 1:
                game_gestures.push_back("scissors"); // 剪刀
                break;
            case 2:
                game_gestures.push_back("paper");    // 布
                break;
        }
    }

    // 打印结果验证
    cout << "生成的秘密数字序列:";
    for (int num : secret_seq) {
        cout << num << " ";
    }
    cout << "\n对应的游戏手势序列:";
    showVect(game_gestures);

    return 0;
}

灵活调整条件

如果你的条件不是模3,而是其他逻辑(比如只处理大于5的数字、或者偶数/奇数判断),只需要修改遍历中的判断部分就行。比如想只保留秘密序列中大于5的数字对应的手势:

for (int num : secret_seq) {
    // 新增条件:只处理大于5的数字
    if (num > 5) {
        switch (num % 3) {
            case 0:
                game_gestures.push_back("rock");
                break;
            case 1:
                game_gestures.push_back("scissors");
                break;
            case 2:
                game_gestures.push_back("paper");
                break;
        }
    }
}

要是你还有更具体的条件需求,可以再细化,但核心逻辑都是遍历源vector元素→判断条件→填充目标vector,这个框架是通用的~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:54:51