[Solved]How to generate random number between two numbers? Qt
-
wrote on 28 Jan 2013, 07:37 last edited by
Hello
Two numbers are taken as inputs & now I want to generate random number between them.
Please tell me how to do it?
Thanks
Zain -
wrote on 28 Jan 2013, 08:00 last edited by
You can use the cstdlib.
See: "cplusplus-doc":http://www.cplusplus.com/reference/cstdlib/rand/
-
wrote on 28 Jan 2013, 08:08 last edited by
Did u tried using qrand() ??
-
wrote on 28 Jan 2013, 08:13 last edited by
random number from interval <a,b>: @x = a + rand() * (b-a)@
-
wrote on 28 Jan 2013, 08:19 last edited by
Example:
MainWindow.h
@
#include <QMainWindow>
class MainWindow : public QMainWindow
{
Q_OBJECTpublic:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();private slots:
void on_pushButton_clicked();private:
Ui::MainWindow *ui;
int High;
int Low;
};
@MainWindow.cpp
@
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <qglobal.h>MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
High = 10;
Low = 5;
}MainWindow::~MainWindow()
{
delete ui;
}void MainWindow::on_pushButton_clicked()
{
qsrand(qrand());
ui->lineEdit->setText(QString::number(qrand() % ((High + 1) - Low) + Low));
}
@ -
wrote on 28 Jan 2013, 08:23 last edited by
Thank u all
Done with it.
-
wrote on 28 Jan 2013, 10:34 last edited by
Note that qrand produces pseudo-random number only. You do want to use something better for e.g. crypto operations.
-
This post is deleted!
-
wrote on 11 Jul 2019, 09:02 last edited by rsarov 7 Nov 2019, 09:03
modern Qt c++ 11
#include <random> #include "QDateTime" int getRand(int min, int max){ unsigned int ms = static_cast<unsigned>(QDateTime::currentMSecsSinceEpoch()); std::mt19937 gen(ms); std::uniform_int_distribution<> uid(min, max); return uid(gen); }
-
wrote on 20 Oct 2019, 08:40 last edited by
Or modern Qt: https://doc.qt.io/qt-5/qrandomgenerator.html :)