產生某個範圍的隨機數

比如要產生 [60-99]的隨機數.

使用rand()函數產生的隨機數是從0(包括0)開始的
我們思考:

[ 0, ?] + 60 =
[60,99]
很明顯,?應該是39.產生[0, 39]的隨機數可以這樣做:rand() % 40  得解.

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

int main()
{
 srand(time(NULL));

 for (int i=0; i!=50; ++i)
 {
  cout << rand() % 40 + 60 << endl;
 }


}

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