C++ Simple 0-10 multiplication flashcard using rand()
我在掌握c ++中rand()和srand()的概念时遇到了麻烦。我需要创建一个显示两个随机数的程序,让用户输入响应,然后将响应与消息匹配,然后执行5次。
我的问题是我怎么使用它,说明说我不能使用time()函数,这似乎在每个有关rand()的在线教程中。
这就是我到目前为止所拥有的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #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的值,我以为种子变量不一定总是不同但不是始终相同?
输出结果如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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()函数),因为它们可能与平台有关。您的程序不应使用任何循环。
顺便说一句,由于这是C ++,因此您应该真正尝试使用
1 2 3 4 5 | #include <functional> #include <random> ... auto rand = std::bind(std::uniform_int_distribution<unsigned>(0, 10), std::default_random_engine()); |
现在,您可以使用
现在,您使用它的方式似乎还不错。所有教程都使用
但是,
编辑后
要获得所需的输出,您需要做的是像这样制作两个种子:
1 2 3 | seed1=(rand()%11); seed2=(rand()%11); cout<<seed1<<" *"<<seed2<<" ="; |
另外,您可以要求用户输入
关于要求:
please do not use any 'automatic' initializer (such as the time()
function), as those are likely to be platform dependent
Your program should not use any loops.
这也是一个非常奇怪的要求。循环是任何程序的基本构建块。这些要求对我来说似乎很奇怪,我想请您的教授或老师澄清一下。
在Windows上,如果使用time(),则可以改用GetTickCount()。
您可以使用不需要种子的rand_s。
在* nix系统上,您可以使用/ dev / random。
(如何使用/ dev / random)
您使用
您可以随心所欲地播种兰德。您会发现大多数教程使用当前时间作为种子,因为每次运行该程序时返回的数字通常是不同的。
如果您确实不能使用
1 2 3 4 | int main(int argc, char* argv[]) { srand(atoi(argv[1])); // Seed with command line argument. } |