Qt中,使用rand,生成随机的vector数组(随机数种子)

5 篇文章 0 订阅

头文件

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

using namespace std;

class Vector_test
{
public:
    Vector_test();

    double rand();
};

源文件

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位
}

结果

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)

除法运算/ 和求余%

对于int类型的函数,必须要有返回值return X,但是不影响qDebug() 和 cout(), 最后一行写一个return 0就可以。

int Test::Out()
{
    int b = 41;
    int a = (41%10);
    double aa = (41%10)/10.0;

     qDebug() << b << a << aa;

     return 0;
}
41 1 0.1
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值