我想生成不同的随机数。我使用了 srand 和 rand ,但在我的输出中有些数字是相同的。
如何使用 srand 生成不同的数字?
#include<iostream>
#include<time.h>
#include <windows.h>
int main(){
time_t t;
std::vector<int> myVector;
srand((unsigned)time(NULL));
for (int i = 0; i < 40; i++){
int b = rand() % 100;
myVector.push_back(b);
std::cout << myVector[i] << std::endl;
}
Sleep(50000);
}
原文由 Michelle 发布,翻译遵循 CC BY-SA 4.0 许可协议
一种简单的方法是将 0-99 之间的所有数字添加到向量中并对其进行洗牌,然后您可以获得所需数量(最多 100 个)的非重复随机数。