【发布时间】:2012-09-02 20:24:06
【问题描述】:
我无法理解 C++ 中的 rand() 和 srand() 的概念。我需要创建一个显示两个随机数的程序,让用户输入响应,然后将响应与消息匹配并执行 5 次。
我的问题是如何使用它,说明说我不能使用 time() 函数,而且这似乎在每个关于 rand() 的在线教程中都有。
这是我目前所拥有的。
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
int seed;
int response;
srand(1969);
seed=(rand()%10+1);
cout<<seed<<" * "<<seed<<" = ";
cin>>response;
cout<<response;
if(response==seed*seed)
cout<<"Correct!. you have correctly answered 1 out of 1."<<endl;
else
cout<<"Wrong!. You have correctly answered 0 out of 1."<<endl;
这只是输出 6*6 或 7*7 之类的东西,我认为种子变量不一定不同但不是一直相同?
这是输出的样子:
3 * 5 =
34
Wrongo. You have correctly answered 0 out of 1.
8 * 1 =
23
Wrongo. You have correctly answered 0 out of 2.
7 * 1 =
7
Correct! You have correctly answered 1 out of 3.
2 * 0 =
2
Wrongo. You have correctly answered 1 out of 4.
8 * 1 =
8
Correct! You have correctly answered 2 out of 5.
Final Results: You have correctly answered 2 out of 5 for a 40% average.
这些是要求:
您的程序应根据需要使用 rand() 生成伪随机数。您可以使用 srand() 来初始化随机数生成器,但请不要使用任何“自动”初始化程序(例如 time() 函数),因为它们可能与平台相关。您的程序不应使用任何循环。
【问题讨论】:
-
好吧,既然您不能在 rand() 中播种一段时间,您是否可以要求用户输入一个数字并将其用作种子或类似内容?
-
或将其设为命令行参数。
-
不要在 C++ 中使用
srand()和rand()。使用<random>,请参阅 oldrinb 的回答。