C++ 實現隨機小數的幾種方法

1.rand()實現方法

#include <iostream>
#include <vector>
using namespace std;
int main()
{
	vector<double> tmpData;
	srand((unsigned)time(NULL));//這裏以當前時間爲種子
	while (i<100)
	{
		double B = (double)(rand() % 10) / 1000;//根據需要設置除數
		tmpData.push_back(B);
		i++;
	}
	for (int i = 0 ; i < 100; i++ )
	{
	   cout<<tmpData[i]<<endl;
	}
	return 0;
}

2.random庫實現

#include<iostream>
#include<random>
#include<ctime>
using namespace std;

int main()
{
	default_random_engine e(time(0));
	uniform_real_distribution<double> u(-1.2,3.5);
	for(int i = 0; i < 10; ++i)
		cout << u(e) << endl;
	return 0;
}

方法二參考鏈接:
原文:https://blog.csdn.net/qq_22080999/article/details/82533368

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章