In Qt, use rand to generate a random vector array (random number seed)

head File

#include <vector>
#include <QDebug>
#include<qmath.h>
#include <QTime>//随机种子

using namespace std;

class Vector_test
{
    
    
public:
    Vector_test();

    double rand();
};

Source File

Vector_test::Vector_test()
{
    
    
    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));//随机数种子(构造函数)

	//vector作为成员变量和局部变量都可以仅声明之后,使用push_back增加元素;
	//但是一维、二维数组要限定规格(比如在1*4或者是3*4的矩阵),必须提前声明是多大的矩阵,编译器无法判断
    vector<double> arrayTest(10);
    qDebug() << arrayTest;

	//对vector数组进行赋值
    for (int i = 0; i < 10; ++i) {
    
    
        arrayTest[i] = rand();
    }
    qDebug() << arrayTest;
}

double Vector_test::rand()
{
    
    

	return (qrand()%10)/10.0+(qrand()%10)/100.0+(qrand()%10)/1000.0;//小数点后3位
//    return (qrand()%10)/10.0;//小数点后1位
//    return (qrand()%10)/10.0+(qrand()%10)/100.0;//小数点后2位

//	  return (qrand()%10)/10.0+(qrand()%10)/100.0+(qrand()%10)/1000.0+(qrand()%10)/10000.0;//小数点后4位
}

result

std::vector(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
std::vector(0.163, 0.111, 0.24, 0.007, 0.046, 0.734, 0.936, 0.885, 0.76, 0.425)

Guess you like

Origin blog.csdn.net/qq_43641765/article/details/111598988