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

随机数组选择器问题:训练肌群随机选择功能异常求助

问题排查与解决:随机肌群选择失效

我一眼就看出问题啦——你的随机数生成器没有初始化种子,这就导致每次程序启动时,生成器的初始状态完全一样,输出的随机数序列也是固定的,所以dice_roll才会一直是2。

问题原因详解

C++的mt19937是伪随机数生成器,它需要一个初始“种子”来启动随机序列。如果像你这样直接声明mt19937 generator;而不设置种子,它会使用默认的固定种子,导致每次运行程序都会生成完全相同的随机数序列。

修复方案

我们需要用真正随机的种子初始化生成器,优先推荐用std::random_device(从系统随机源获取种子),如果你的系统不支持它,也可以用当前时间作为备选方案。

修改后的完整代码

#include <iostream>
#include <string>
#include <random>
#include <chrono> // 时间种子方案需要的头文件

using namespace std;

int main() {
    int muscleGroup;
    string chest[2] = {"Benchpress 4x2", "Pushups 10x4"};
    string legs[2] = {"Squat 8x4", "Leg extension 10x3"};
    string back[2] = {"Pullup 3x8", "Rows 10x3"};

    // 方案1:优先使用random_device初始化种子(更贴近真随机)
    random_device rd;
    mt19937 generator(rd());

    // 方案2:若系统不支持random_device,用当前时间作为种子
    // unsigned seed = chrono::system_clock::now().time_since_epoch().count();
    // mt19937 generator(seed);

    uniform_int_distribution<int> distribution(0, 2);
    int dice_roll = distribution(generator);

    if (dice_roll == 0) {
        cout << "You are training: Chest" << endl;
        cout << "Your exercises are going to be written below!" << endl;
        // 顺便输出对应肌群的训练内容
        for (const auto& exercise : chest) {
            cout << "- " << exercise << endl;
        }
    } else if (dice_roll == 1) {
        cout << "You are training: Legs" << endl;
        cout << "Your exercises are going to be written below!" << endl;
        for (const auto& exercise : legs) {
            cout << "- " << exercise << endl;
        }
    } else if (dice_roll == 2) {
        cout << "You are training: Back" << endl;
        cout << "Your exercises are going to be written below!" << endl;
        for (const auto& exercise : back) {
            cout << "- " << exercise << endl;
        }
    }

    return 0;
}

额外优化建议

  • 补充必要头文件:你的原始代码缺少#include <iostream>、#include <random>和#include <string>,这些是编译必需的。
  • 结构化存储数据:可以用std::vector<std::pair<std::string, std::vector<std::string>>>来统一存储肌群和训练内容,后续扩展更多肌群会更方便。
  • 复用输出逻辑:把输出训练内容的代码抽成函数,避免重复的cout代码块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:45:03