我做错了什么?谢谢.
码
#include <fstream>#include <ctime>#include <cstdlib>using namespace std;const char duom[] = "U1.txt";const char rez[] = "U1_rez.txt";voID num_gen(int & x,int & y);int main(){ srand(time(NulL)); int x,y; ifstream fd(duom); fd >> x >> y; fd.close(); ofstream fr(rez); for(int j = 1; j <= 4; j++){ num_gen(x,y); fr << x << " + " << y << " = "<< x + y << endl; fr << x << " - " << y << " = "<< x - y << endl; fr << x << " * " << y << " = "<< x * y << endl; fr << x << " / " << y << " = "<< x / y << endl; fr << "************" << endl; } fr.close(); return 0;}voID num_gen(int & x,int & y){ x = 3 + (rand() % 10); y = 3 + (rand() % 10);}
结果
4 8 = 12
4 – 8 = -4
4 * 8 = 32
4/8 = 0
************
4 9 = 13
4 – 9 = -5
4 * 9 = 36
4/9 = 0
************
9 11 = 20
9 – 11 = -2
9 * 11 = 99
9/11 = 0
************
12 8 = 20
12 – 8 = 4
12 * 8 = 96
12/8 = 1
************
#include <iostream>#include <random> // for default_random_engine & uniform_int_distribution<int>#include <chrono> // to provIDe seed to the default_random_engineusing namespace std;default_random_engine dre (chrono::steady_clock::Now().time_since_epoch().count()); // provIDe seedint random (int lim){ uniform_int_distribution<int> uID {0,lim}; // help dre to generate nos from 0 to lim (lim included); return uID(dre); // pass dre as an argument to uID to generate the random no}int main(){ for (int i=0;i<10;++i) cout<<random(10)<<" "; return 0;}
上述代码的其中一项输出是: –
8 5 0 4 2 7 9 6 10 8
请参阅,数字从0到10不等.根据您所需的输出,在uniform_int_distribution中给出限制.这件事很少失败&你可以在更大的范围内生成随机数,而不必担心像你那样令人难以置信的输出.
总结以上是内存溢出为你收集整理的C在循环内生成随机数全部内容,希望文章能够帮你解决C在循环内生成随机数所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)