1. 程式人生 > >C C++程式設計產生指定範圍內的隨機數

C C++程式設計產生指定範圍內的隨機數

C/C++程式設計產生指定範圍內的隨機數,直接上個小程式:

#include <stdlib.h> // 對應於C++中cstdlib
#include <time.h> // ctime
#include <stdio.h>

int main()
{
	srand(time(NULL));
	int low = 0, high = 100;
	int rnum = rand() % (high - low + 1) + low;
	printf("random number = %d\n", rnum);
	system("pause");
	return 0;
}

呼叫rand()會產生[0,32757]之間的隨機數,(high - low)的絕對值不能超過32767。