就像在 Java 中一样,(Math . random * ) 语句在 C++ 中有没有办法输入数组数字?
例如,我想在 C++ 中使用随机数输入从 6 到 89 的数字。将它们分配到数组中。
我知道如何对数字进行排序,但我只想知道如何生成随机数以使我的生活更轻松。
我对编程很生疏,我乐于接受任何批评,但我希望得到直截了当的回应。
最佳答案
使用srand
为随机数生成器提供种子,然后使用rand
获取随机数。
例如,以下程序使用您请求范围内的随机值填充一个数组:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main (void) {
int xyzzy[10];
// Seed the generator.
std::srand (time (0));
// Populate the array.
for (int i = 0; i < sizeof(xyzzy) / sizeof(*xyzzy); i++)
xyzzy[i] = 6 + (std::rand() % 84);
// Print the array.
for (int i = 0; i < sizeof(xyzzy) / sizeof(*xyzzy); i++)
std::cout << xyzzy[i] << "\n";
return 0;
}
这输出(在我的例子中):
59
51
84
83
58
85
83
25
50
22
请记住,由于这些随机数的生成方式,它们的属性可能并不完美,但除非您是统计学家或密码学家,否则它们应该没问题。
关于c++ - 在 C++ 中是否有一种用于将值随机输入数组的库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8045586/