1.rand() 亂數函式
當使用rand()時,需要include它的標頭擋 <stdlib.h>。
例如
取得1-10的亂數:r=(rand()%10)+1
取得1-100的亂數:r=(rand()%100)+1
取得100-1000的亂數:r=(rand()%901)+100
範例
#include<stdio.h>
#include <stdlib.h>
int main(void)
{
int r;
r=(rand()%100)+1;
printf("The Random Number is %d .\n", r);
system("pause");
return 0;
}
當程式執行幾次你會發現,取得的亂數都是一樣,
這是因為rand()都是以0為開始,
所以應該在rand() 前面加上srand() 。
2.srand() 函式
使用方式 srand(time(0)) ,標頭檔<time.h>
#include<stdio.h>
#include <stdlib.h>
#include<time.h>
int main(void)
{
int r;
srand(time(0));
r=(rand()%100)+1;
printf("The Random Number is %d .\n", r);
system("pause");
return 0;
}
參考資料:
http://dhcp.tcgs.tc.edu.tw/c/p005.htm
http://fred-zone.blogspot.tw/2006/03/c-rand.html
文章標籤
全站熱搜

以下是您的部分文章內容 取得1-9的亂數:r=(rand()%10)+1 怎麼看都是1-10的亂數...
打錯了 沒注意到 謝謝提醒:D