注册 登录
编程论坛 C语言论坛

每次生成的随机数都是一样的 有哪位大神能告诉我为什么嘛

lfh1002 发布于 2020-04-05 18:57, 2673 次点击

#include <iostream>
 #include<string>
#include<stdlib.h>
 #include<time.h>  
using namespace std;
int main() {
    for (int i = 0; i <= 8; i++) {
        for (int j = 0; j <= 8; j++) {
            unsigned srand(time(0));
         unsigned int t = rand() % 101;
             cout << t << '\t';

        }
        cout << endl;
}
    return 0;
}
5 回复
#2
lin51616782020-04-05 19:04
            unsigned srand(time(0));
放在循环外面
#3
sherlocked132020-04-05 19:12
这好像是c++吧,不是应该放在c++论坛里么
#4
lfh10022020-04-05 19:20
回复 2楼 lin5161678
还是不行
#5
lin51616782020-04-05 21:33
以下是引用lfh1002在2020-4-5 19:20:18的发言:

还是不行

代码呢?
#6
叶纤2020-04-12 16:21
发现这位小兄弟,好可怜,问了c++和c都没问出个答案,本人在c++还吐槽了几句,突然想到我刚学习c++的时候也是很懵逼的
程序代码:


#include <iostream>

 #include<string>
#include<cstdlib>

 #include<ctime>
using namespace std;
int main() {
    srand (( unsigned int) time(0));//种子只需要播种一次就可以了
    for (int i = 0; i <= 8; i++) {
        for (int j = 0; j <= 8; j++) {

         unsigned int t = rand() % 101;
             cout << t << '\t';

        }
        cout << endl;
}
    return 0;
}



上面的是语法上偏c
程序代码:


 #include<string>
#include<cstdlib>
#include<ctime>
#include<random>
using namespace std;
int main() {
    mt19937 mt{static_cast<mt19937::result_type>(time(nullptr))};
    uniform_int_distribution mtr{0,101};//统一分配
   
//++17前要要这样写

    for (size_t i = 0; i <= 8; i++)
    {
        for (size_t  j = 0; j <= 8; j++)
        {

         unsigned int t = mtr(mt) ;
             cout << t << '\t';

        }
        cout << endl;
}
    return 0;
}


这种是c++比较爱的一种算法
1