C++实现游戏选择器多项目随机选取重复输出问题求解
问题根因
多选取模式重复输出同一项目,是代码里4处明显错误导致的:
- 随机种子重复初始化:
srand(time(0))写在pickGame()内部,每次调用选取函数都会重置种子。time(0)返回的是秒级时间戳,程序短时间内多次调用时拿到的种子值完全相同,生成的随机索引自然一致。 - 循环逻辑完全错误:
gamesNumber()里的while循环仅在t == gamesCount时触发一次选取,根本没有按输入次数循环执行选取操作。 - 无去重逻辑:即便修复循环和随机数问题,多次随机抽样也可能抽到同一个索引,没有做已选项目的排除处理。
- 头文件拼写/引用错误:
#include <avector>是笔误,正确写法为#include <vector>;引入了<random>但未使用,同时缺少<string>、<ctime>头文件,部分编译器下会直接编译报错。
修复步骤
- 将随机种子初始化语句移到
main()函数入口,整个程序运行周期内仅执行一次 - 重写
gamesNumber()的循环逻辑,按用户输入的选取次数循环抽样 - 新增已选标记数组,每次抽样后标记对应索引,抽到已选索引时重新生成随机值,确保返回项目不重复
- 增加边界校验:如果用户输入的选取数量大于已录入项目总数、或小于等于0,直接抛出提示避免死循环/逻辑异常
- 修正头文件错误,删除冗余全局变量
修复后可直接运行的代码
/* Me 6-14-22 Game Selector */ #include <iostream> #include <vector> #include <string> #include <ctime> using namespace std; vector<string> gameList; bool going = true; string usrInp = ""; int gamesCount = 0; int input() { while(going){ cout << "Please enter your Items:" << endl; getline(cin, usrInp); cout << endl; if(usrInp == "Done" || usrInp == "done"){ going = false; return 0; } gameList.push_back(usrInp); } } void pickGame(vector<bool>& selected) { int generated; do { generated = rand() % gameList.size(); } while (selected[generated]); selected[generated] = true; cout << "- " << gameList[generated] << endl; } void gamesNumber(){ cout << "Please enter the amount of games you want :" << endl; cin >> gamesCount; if(gamesCount > gameList.size()){ cout << "错误:选取数量不能超过已录入的项目总数" << endl; return; } if(gamesCount <= 0){ cout << "错误:选取数量必须大于0" << endl; return; } vector<bool> selected(gameList.size(), false); cout << endl << "选中结果:" << endl; for(int i = 0; i < gamesCount; i++){ pickGame(selected); } } int main() { srand(time(0)); input(); gamesNumber(); return 0; }
内容的提问来源于stack exchange,提问作者Luke8414
相关产品推荐
相关产品推荐

