比如要產生 [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;
}
}