如何在0-100的4个不同随机数序列中随机放置固定数86?
解决方案
可以通过先构建包含86的数字集合,再随机打乱顺序的方式实现,同时还能解决原代码中未处理重复数字的问题。具体步骤如下:
- 初始化存储结构,先放入必须包含的86。
- 生成3个随机数,确保每个数在0-100范围内、不等于86,且不与已生成的数字重复。
- 打乱存储结构内的元素顺序,让86的位置随机化。
- 输出最终序列。
以下是完整的实现代码:
#include <iostream> #include <cstdlib> #include <ctime> #include <vector> #include <algorithm> using namespace std; int main() { srand((unsigned)time(NULL)); vector<int> nums; nums.push_back(86); // 先加入必须包含的86 // 生成3个不重复且不等于86的随机数 while (nums.size() < 4) { int random_num = rand() % 101; // 检查数字是否已存在或等于86 bool exists = false; for (int num : nums) { if (num == random_num) { exists = true; break; } } if (!exists) { nums.push_back(random_num); } } // 打乱数组顺序,让86位置随机 random_shuffle(nums.begin(), nums.end()); // 输出序列 for (int num : nums) { cout << num << endl; } return 0; }
代码说明:
- 使用
vector存储数字,方便动态添加和打乱操作。 - 循环生成随机数时,通过遍历已存在的数字确保不重复,同时排除86。
random_shuffle函数会随机交换容器内的元素位置,彻底让86的位置不可预测。- 补充了
#include <ctime>,原代码使用time(NULL)但未包含对应头文件,可能导致编译错误。
如果不想使用容器和算法库,也可以用普通数组手动实现打乱逻辑:
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand((unsigned)time(NULL)); int nums[4]; nums[0] = 86; int count = 1; // 生成3个不重复的随机数 while (count < 4) { int random_num = rand() % 101; bool exists = false; for (int i = 0; i < count; i++) { if (nums[i] == random_num) { exists = true; break; } } if (!exists) { nums[count++] = random_num; } } // 手动打乱数组:随机交换元素位置 for (int i = 3; i > 0; i--) { int j = rand() % (i + 1); swap(nums[i], nums[j]); } // 输出 for (int num : nums) { cout << num << endl; } return 0; }
内容的提问来源于stack exchange,提问作者user19627042
相关产品推荐
相关产品推荐

