c++ 隨機生成區間范圍內的數


要取得 [a,b) 的隨機整數,使用 (rand () % (b-a))+ a;

要取得 [a,b] 的隨機整數,使用 (rand () % (b-a+1))+ a;

要取得 (a,b] 的隨機整數,使用 (rand () % (b-a))+ a + 1;

通用公式:a + rand () % n;其中的 a 是起始值,n 是整數的范圍。

要取得 a 到 b 之間的隨機整數,另一種表示:a + (int) b * rand () / (RAND_MAX + 1)。

要取得 0~1 之間的浮點數,可以使用 rand () /double (RAND_MAX)。
示例代碼:

#include <string>
#include <iostream>
#include <time.h>
using namespace std;
 //使用模板類實現函數RandT,生成min,max直接的數。
template<typename T>
T RandT(T _min, T _max)
{
	T temp;
	if (_min > _max)
	{
		temp = _max;
		_max = _min;
		_min = temp;
	}
	return rand() / (double)RAND_MAX *(_max - _min) + _min;
}
 
int _tmain(int argc, _TCHAR* argv[])
{
	srand((unsigned)time(NULL));
	for (int i = 0; i < 10; i++)
		cout << RandT<double>(1.0, 5.0) << endl;
 
	for (int i = 0; i < 10;i++)
		cout << RandT<int>(1, 10) << endl;
 
	return 0;
}

————————————————
版權聲明:本文為CSDN博主「hellokandy」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/hellokandy/article/details/90045187


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM