C++ 我想生成一些矩阵,并用随机数填充它
嗨,伙计们,我想用随机数生成一些5x5的矩阵,但我做的这段代码只是一遍又一遍地打印同一个矩阵,有什么问题吗?(我正在学习c++),这段代码只是反复打印相同的矩阵,而不是每个矩阵中的不同数字C++ 我想生成一些矩阵,并用随机数填充它,c++,arrays,matrix,random,numbers,C++,Arrays,Matrix,Random,Numbers,嗨,伙计们,我想用随机数生成一些5x5的矩阵,但我做的这段代码只是一遍又一遍地打印同一个矩阵,有什么问题吗?(我正在学习c++),这段代码只是反复打印相同的矩阵,而不是每个矩阵中的不同数字 #include <iostream> #include <string> #include <sstream> #include <ctime> #include <iomanip> #include <cstdlib> using
#include <iostream>
#include <string>
#include <sstream>
#include <ctime>
#include <iomanip>
#include <cstdlib>
using namespace std;
bool verif(int carton[5][5], int f, int c, int nume){
for(f=0;f<5;f++){
for(c=0;c<5;c++){
if(nume==carton[f][c]){
return false;
}
}
}
return true;
}
int i,cant,nume;
int main()
{
ingresa:
int j,cant;
cout<< "type the number of bingo cards you want: ";
cin>>cant;
if(cant>100){
cout<<"ERROR the max number of bingo cards is 100:"<<endl;
goto ingresa;
}
for(i=1;i<=cant;i++){
cout<<endl;
cout<< "BINGO #"<<i<<endl;
int carton[5][5];
int f,c,nume;
srand(time(NULL));
for(f=0;f<5;f++){
for(c=0;c<5;c++){
nume=1+rand()%25;
carton[f][c]=nume;
while(verif(carton,5,5,nume)==false){
nume=1+rand()%25;
}
carton[f][c]=nume;
}
}
for(f=0;f<5;f++){
for(c=0;c<5;c++){
cout<<setw(3)<<carton[f][c]<<" ";
}
cout<<endl;
}
}
}
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
bool-verif(int-carton[5][5],int-f,int-c,int-nume){
对于(f=0;f100){
cout主要问题是您多次调用了srand()
,将随机数生成器的状态重置为相同的值(除非您运气好,并且时钟在迭代之间每隔一秒进行一次)。您应该只为伪随机数生成器种子设定一次
次要细节:
- 填充数组的算法很昂贵。与其生成一个随机数并测试该数是否已被取下,不如先生成顺序为(1-25)的数,然后再生成数组
- 不要使用
srand()
&rand()
。标准库中有更好的随机生成器,如
- 不要使用
goto
。在(true)
循环时执行,并在用户输入有效数字时将其中断
#包括
#包括
#包括
#包括
int main(){
std::mt19937 prng(std::random_device{}());//种子prng
国际纸箱[5][5];
//用1-25填充数组
标准:物联网(&纸箱[0][0],&纸箱[0][0]+25,1);
//将订单适当地随机排列
标准:洗牌(&carton[0][0],&carton[0][0]+25,prng);
//您可以使用prng生成[1,25]范围内的随机数
//在uniform_int_distribution的帮助下:
标准:均匀分布区(1,25);
std::库和算法乍一看似乎是显而易见的开始阅读的地方。bool-verif(int-carton[5][5],
-不要试图像那样传递C样式的数组。使用std::数组
或std::vector
。srand(time(NULL))
这是一个非常糟糕的(第二分辨率)一个相当糟糕的随机数生成器的种子。不要在新代码中使用srand
/rand
。也许我错了,但我只看到在您的程序中创建了一个矩阵。
#include <algorithm>
#include <iostream>
#include <numeric>
#include <random>
int main() {
std::mt19937 prng(std::random_device{}()); // A seeded PRNG
int carton[5][5];
// fill the array with 1-25
std::iota(&carton[0][0], &carton[0][0] + 25, 1);
// make the order properly random
std::shuffle(&carton[0][0], &carton[0][0] + 25, prng);
// You can use the prng to generate a random number in the range [1,25]
// with the help from uniform_int_distribution:
std::uniform_int_distribution<int> dist(1, 25);
std::cout << "A random number 1-25: " << dist(prng) << '\n';
}