c++生成随机数
随机浮点数的函数
代码
main.cpp
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include "random.h"
using namespace std;
int main()
{
int a = 0;
int b = 100;
int c = 0;
int d = 50;
srand((int)time(0)); //随机数种子,只在生成随机数之前执行一次
c = (rand() % (b - a)) + a; //[a ,b)的随机整数
// c = (rand() % (b - a + 1)) + a; //[a ,b]的随机整数
// c = (rand() % (b - a)) + a; //(a ,b)的随机整数
// c = (rand() % (b - a)) + a + 1; // (a ,b]的随机整数
// c = rand() % d + a; //随机整数,a是起始数,d是范围
// c = GenerateRandomNumber(1, 100); //生成1到100的随机浮点数
cout << c << endl;
return 0;
}
random.h
double GenerateRandomReal(double low, double high);
random.cpp
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
//生成low到high的随机浮点数
double GenerateRandomReal (double low, double high)
{
double m_d;
m_d = (double)rand() / (double)RAND_MAX; //生成0到1的浮点数
return low + m_d * (high - low);
}
接下来是我写的随机数生成库,供大家参考
源代码
main.cpp
#include <iostream>
using namespace std;
#include "random.h"
int main()
{
int i;
Randomize();
for (i = 0; i <= 10; i++)
{
int t = GenerateRandomNumber(1, 100);
cout << t << " ";
}
cout << endl;
for (i = 0; i <= 10; i++)
{
double d = GenerateRandomReal(1, 100);
cout << d << " ";
}
cout << endl;
return 0;
}
random.h
void Randomize();
int GenerateRandomNumber(int low,int high);
double GenerateRandomReal(double low,double high);
random.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void Randomize()
{
srand((int)time(0));
}
int GenerateRandomNumber(int low, int high)
{
double m_d;
if (low > high)
{
cout << "GenerateRandomNumber:error,make sure low <= high" << endl;
exit(1);
}
m_d = rand() / ((double)RAND_MAX + 1.0);
return low + (int)(m_d * ((double)high - (double)low + 1.0));
}
double GenerateRandomReal(double low, double high)
{
double m_d;
if (low > high)
{
cout << "GenerateRandomReal:error,make sure low <= high" << endl;
exit(1);
}
m_d = (double)rand() / (double)RAND_MAX;
return low + m_d * (high - low);
}
这就是c++生成随机数的实现了,如有错误,欢迎指正