我无法理解 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() 函数),因为它们可能与平台相关。您的程序不应使用任何循环。