33,311
社区成员
发帖
与我相关
我的任务
分享
/***
*rand.c - random number generator
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
* defines rand(), srand() - random number generator
*
*******************************************************************************/
#include <cruntime.h>
#include <mtdll.h>
#include <stddef.h>
#include <stdlib.h>
/***
*void srand(seed) - seed the random number generator
*
*Purpose:
* Seeds the random number generator with the int given. Adapted from the
* BASIC random number generator.
*
*Entry:
* unsigned seed - seed to seed rand # generator with
*
*Exit:
* None.
*
*Exceptions:
*
*******************************************************************************/
void __cdecl srand (
unsigned int seed
)
{
_getptd()->_holdrand = (unsigned long)seed;
}
/***
*int rand() - returns a random number
*
*Purpose:
* returns a pseudo-random number 0 through 32767.
*
*Entry:
* None.
*
*Exit:
* Returns a pseudo-random number 0 through 32767.
*
*Exceptions:
*
*******************************************************************************/
int __cdecl rand (
void
)
{
_ptiddata ptd = _getptd();
return( ((ptd->_holdrand = ptd->_holdrand * 214013L
+ 2531011L) >> 16) & 0x7fff );
}
#include <iostream>
#include "stdafx.h"
using namespace std;
void main(void)
{
cout << "打印1~10之间的技术" << endl;
for (int count = 1; count <= 10; count++)
{
if (count % 2 == 0) //判断是否是偶数
continue; //跳过剩余循环部分
cout << count << " ";
}
cout << endl;
cout << "产生随机数和是:"<<endl;
int max = 0;
int tmp(0);
srand(max); //随机数产生种子
while (true) //无限循环
{
tmp = rand() % 200; //随机数在200内产生
cout << tmp;
max += tmp; //max=max+tmp,随机数进行累加
if (max > 1000)
{
cout << " = " << max << endl;
break; //跳出while 循环
}
else {
cout << "+";
}
}
system("pause");
}
将srand放在while循环外。参考一下吧
如果随机产生多个数,有两个数一样那是可能的,随机数,也可能是两个数一样的,有这样的概率。但是如果产生的所有随机值都一样,那么应该是种子的问题。