VC++如何得到不同的随机数,srand我试过了,每次产生的随机数都一样。

如题所述

mfc生成随机数
[此问题的推荐答案]
此段程序可以满足你的要求,可以运行,自己有什么另外的用法,修改一下就行了
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
using std::cout;
using std::endl;
using std::ios;
#include <fstream>
using std:fstream;
#include <iomanip>
using std::setw;

int main(int argc, char* argv[])
{
printf("Hello World!\n");
int i=0;
int k=0;
srand((unsigned)time( NULL ));
ofstream ofs("aaa.txt",ios:ut);
for(int j=1;j<=90;j++)
{
k=rand()%200+1;
printf("%10d",k);
ofs<<setw(10)<<k;
if(j%3 == 0)
{
printf("\n");
ofs<<endl;//三个数换行
}
}
ofs.close();
return 0;
}

文件操作就这么几行:
ofstream ofs("aaa.txt",ios:ut);
ofs<<setw(10)<<k;
ofs<<endl;
ofs.close();
随机数操作:
srand((unsigned)time( NULL ));
k=rand()%200+1;

或者试试下面的
使用rand函数获得随机数。rand函数返回的随机数在0-RAND_MAX(32767)之间。
例子:
/* RAND.C: This program seeds the random-number generator
* with the time, then displays 10 random integers.
*/

#include <stdio.h>
#include <stdlib.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() );
}

在调用这个函数前,最好先调用srand函数,如srand( (unsigned)time( NULL ) ),这样可以每次产生的随机数序列不同。
如果要实现类似0-1之间的函数,可以如下:
double randf()
{
return (double)(rand()/(double)RAND_MAX);
}

如果要实现类似Turbo C的random函数,可以如下:
int random(int number)
{
return (int)(number/(float)RAND_MAX * rand());
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-04-04
#include<time.h>
srand((unsigned int)time(NULL)); //用当前时间做种子,解决种子固定问题
int a=rand();本回答被网友采纳
相似回答