弱弱的问题

fzs0206 2009-06-12 03:38:14
一个弱弱的问题我是新手 有那个大虾能停下您的鼠标帮我解答下 随机数字是怎么回事 我老是无法理解 我自己写个产生随机数字的程序老是给我报错,以前我做java的感觉C++的随机数字来的比java复杂啊.
...全文
39 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
Jalien 2009-06-12
  • 打赏
  • 举报
回复
很多东西其实查查msdn就知道了。

lz你在msdn里面输入rand你就会找到。下面是我输入rand会出后的例子。

// crt_rand.c
// This program seeds the random-number generator
// with the time, then exercises the rand function.
//

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

void SimpleRandDemo( int n )
{
// Print n random numbers.
int i;
for( i = 0; i < n; i++ )
printf( " %6d\n", rand() );
}

void RangedRandDemo( int range_min, int range_max, int n )
{
// Generate random numbers in the half-closed interval
// [range_min, range_max). In other words,
// range_min <= random number < range_max
int i;
for ( i = 0; i < n; i++ )
{
int u = (double)rand() / (RAND_MAX + 1) * (range_max - range_min)
+ range_min;
printf( " %6d\n", u);
}
}

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

SimpleRandDemo( 10 );
printf("\n");
RangedRandDemo( -100, 100, 10 );
}



输出:

22036
18330
11651
27464
18093
3284
11785
14686
11447
11285

74
48
27
65
96
64
-5
-42
-55
66


学习随机数还有比这好的例子吗?
霍大脚 2009-06-12
  • 打赏
  • 举报
回复

研究下这两头文件
#include<cstdlib>
#include<ctime>
pathuang68 2009-06-12
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 lianshaohua 的回复:]
C/C++ code
#include "stdafx.h"
#include <stdlib.h>
#include <time.h>
#include "RandomNumber.h"
using namespace RN;

RandomNumber::RandomNumber()
{
srand((unsigned)time(NULL));//调用标准C的函数产生随机数,
}

int RandomNumber::getRandomNumber()
{

int res=rand()%100;
if(res%2==0)
{
res++;
}
res+=100;
return res;
}

RandomNumber::~RandomN…
[/Quote]
正解了
ztenv 版主 2009-06-12
  • 打赏
  • 举报
回复
msdn写得比较详细,如果你想用托管代码,可以考虑Random类;
fzs0206 2009-06-12
  • 打赏
  • 举报
回复
谢谢各位 尤其是三楼的 学习了
zhouxingyu896 2009-06-12
  • 打赏
  • 举报
回复
支持3楼的
ztenv 版主 2009-06-12
  • 打赏
  • 举报
回复

#include "stdafx.h"
#include <stdlib.h>
#include <time.h>
#include "RandomNumber.h"
using namespace RN;

RandomNumber::RandomNumber()
{
srand((unsigned)time(NULL));//调用标准C的函数产生随机数,
}

int RandomNumber::getRandomNumber()
{

int res=rand()%100;
if(res%2==0)
{
res++;
}
res+=100;
return res;
}

RandomNumber::~RandomNumber()
{
}
coverallwangp 2009-06-12
  • 打赏
  • 举报
回复
把你的程序贴出来看看

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧