舒尔上海专卖店:怎样得到随机数???

来源:百度文库 编辑:杭州交通信息网 时间:2024/04/27 13:33:05
#include<iostream>
#include<stdlib.h>
using namespace std;

int main()
{
int i;
i = rand();
cout<<rand()<<endl;
getchar();
return 0;
}
vc++每次都是一个相同的数;怎么办?
我想得到一定范围的随机数比如0~50用什么办法?
要得到一个长度,内容随即的字符串,怎么办?
求源程序

更简单方法:

#include<iostream>
#include<stdlib.h>
using namespace std;
void main()
{ int a;

while (1)
{
a=rand();
if (a<50){
cout << \"The Random number is \"<<a<<endl;
break; }

}
}
//最后输出的a就是小于50的正整数.

你没给种子,不能产生随机效果.
时间种子比较好.
下面是MSDN中的一段,也许对你有帮助.
/* RAND.C: This program seeds the random-number generator
* with the time, then displays 10 random integers.
*/

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void main( void )
{
int i;

/* Seed the random-number generator with current time so that
* the numbers will be different every time we run.
*/
srand( (unsigned)time( NULL ) );

/* Display 10 numbers. */
for( i = 0; i < 10;i++ )
printf( " %6d\n", rand()%51);
}

Example

/* RAND.C: This program seeds the random-number generator
* with the time, then displays 10 random integers.
*/

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void main( void )
{
int i;

/* Seed the random-number generator with current time so that
* the numbers will be different every time we run.
*/
srand( (unsigned)time( NULL ) );

/* Display 10 numbers. */
for( i = 0; i < 10;i++ )
printf( " %6d\n", rand() );
}

Output

6929
8026
21987
30734
20587
6699
22034
25051
7988
10104