C++rand()用法

用法

// 記得包含標準庫頭文件
#include <stdlib.h>
// 就表示  a~b 之間的一個隨機整數
rand() % (b-a+1)+ a ;    

舉例

#include <iostream>
#include <stdlib.h>

int main ()
{
	// 生成(10,100)之內的隨機數
	for (int i=0;i<3;i++)
	{
		std::cout<<rand() %91+10<<std::endl;
	}
	// 生成(0,1)之內的小數,精確到兩位小數
	for (int i=0;i<3;i++)
	{
		int a = rand()%101;
		float a_ = (float)a/100;
		std::cout<<a_<<std::endl;
	}
}

輸出:

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