如何生成多个随机数?
How to generate multiple random numbers?
目前,该程序仅生成一个打印3次的随机数。如何让它打印三个不同的随机数?
同样,我很惊讶即使我使用了 time(0),我也不需要 ctime 标头。
//This program generates three random numbers.
#include <iostream>
#include <cstdlib>
using std::endl;
using std::cout;
int main() {
unsigned number;
srand(time(0));
number = rand() % 10 + 1;
cout << number << " ";
cout << number << " ";
cout << number << endl;
return 0;
}
目前,该程序仅生成一个打印 3 次的随机数。如何让它打印三个不同的随机数?
你似乎有一个严重的误解
number = rand() % 10 + 1;
确实如此。
在你完成该任务时
rand() % 10 + 1
计算number
的值并将其存储一次到上面提到的行中的变量中。
进一步访问number
将不再触发该评估。
如果您想在每次访问特定"变量">时都进行评估,则可能需要改用lambda 函数:
#include <cstdlib>
#include <ctime>
#include <iostream>
int main() {
std::srand(std::time(nullptr));
auto number = []() {
return std::rand() % 10 + 1;
};
std::cout << number() << " ";
std::cout << number() << " ";
std::cout << number() << std::endl;
}
这是一个现场演示
另外,我很惊讶即使我使用了
time(0)
,我也不需要ctime标头。
它发生在特定的编译器实现中,你很幸运,并且已经使用的标准标头之一已经包含time(0)
调用所需的ctime
标头。
你应该写的安全和便携的方式
#include <ctime>
// ...
std::time(nullptr)
// ...
您只设置number
一次,它将继续是您分配给它的随机数,直到您为其分配其他内容,例如来自rand()
的另一个随机数
/This program generates three random numbers.
#include <iostream>
#include <cstdlib>
using std::endl;
using std::cout;
int main()
{
unsigned number;
srand(time(0));
number = rand() % 10 + 1;
cout << number << " ";
number = rand() % 10 + 1;
cout << number << " ";
number = rand() % 10 + 1;
cout << number << endl;
return 0;
}
C++ 中的赋值不是每次使用变量时应用的公式。 因此,当您执行此操作时:
number = rand() % 10 + 1;
将值分配给number
一次,在程序中出现该值的点。
如果要获取更多随机数,则需要多次调用rand
并分配给number
。
number = rand() % 10 + 1;
cout << number << " ";
number = rand() % 10 + 1;
cout << number << " ";
number = rand() % 10 + 1;
cout << number << endl;
解决方案:
#include <iostream>
#include <cstdlib>
using std::endl;
using std::cout;
int main()
{
unsigned number;
srand(time(0));
number = rand() % 10 + 1;
cout << number << " ";
number = rand() % 10 + 1;
cout << number << " ";
number = rand() % 10 + 1;
cout << number << endl;
return 0;
}
你的代码片段返回相同的随机三次的原因是,
//This program generates three random numbers.
#include <iostream>
#include <cstdlib>
using std::endl;
using std::cout;
int main()
{
unsigned number;
srand(time(0));
number = rand() % 10 + 1;
cout << number << " ";
cout << number << " ";
cout << number << endl;
return 0;
}
"随机"的值只分配给数字一次,在再次分配之前,它将保持不变。
希望你把我弄对了;)
相关文章:
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 半随机数生成C++
- 有没有办法在 c++ 中同时生成随机数?如果没有,是否有解决方法?
- 我想生成许多矩阵并用随机数填充它
- 为什么 rand 不在我的代码中生成随机数?
- 从给定种子生成相同的随机数序列C++
- 随机数生成函数说明
- C++ 尝试生成随机数时弹出警告帮助?
- 从给定的随机数组值生成随机数 Arduino程序C++
- 如何在个人计算机和群集 (c++) 上生成相同的随机数
- 测量时间以在 c++ 中生成更好的随机数
- C++:使用Stroustrup示例生成随机数?
- 在 C++11 中生成随机数组
- 使用给定种子生成的随机数序列是否保证在标准版本中相同?
- 在一定范围内生成随机数,其中一定百分比为特定值
- 在random_device和seed_seq之间做出决定,为多个随机数序列生成种子
- 如何使用伪随机数生成器生成一组特定的数字
- 无重复的随机数组生成
- 给定二进制随机数生成器生成随机浮点数的正确方法
- c++中的随机数组生成