如何生成多个随机数?

How to generate multiple random numbers?

本文关键字:随机数 何生成      更新时间:2023-10-16

目前,该程序仅生成一个打印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;
}

"随机"的值只分配给数字一次,在再次分配之前,它将保持不变。

希望你把我弄对了;)