C++ 随机数函数

介绍C++随机数函数

函数rand()是C++中的随机函数。

注意:rand()中不能加参数!

 1 #include<iostream>
 2 using naemspace std;
 3 int main(){
 4     int x,y;
 5     cout<<"随机数区间:";
 6     cin>>x>>y;
 7     printf("产生随机数:%d",x+1+rand()%(y-x));
 8     system("pause");
 9     return 0;
10 }

random1

 rand()将产生一个随机数(据说是从0到32767,所以后面的模别太大)。

%(y-x)是对(y-x)求余。产生的是0~(y-x)-1。
例如输入10,20将输出10~20随机数。

你还可以加个种子:

#include<iostream>
#include<ctime>
using naemspace std;
int main(){
    int x,y;
    srand(time(0));
    cout<<"随机数区间:";
    cin>>x>>y;
    printf("产生随机数:%d",x+1+rand()%(y-x));
    system("pause");
    return 0;
}

random2

posted @ 2012-07-09 11:40  TonyFang  阅读(577)  评论(0编辑  收藏  举报