谁来帮我找一下错误

cybot7yxy 2010-07-14 08:58:19
我想写一个随机数生成器,指定上限就可以生成上限以内的随机数。
我的程序如下,但运行效果很不理想,每次生成的都是一样的数,谁来帮我看看是哪里除了问题?

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int generateRandomNum(int upperLimit);
int main()
{
for(int i=0;i<10;i++)
cout<<generateRandomNum(30)<<endl;
return 0;
}
int generateRandomNum(int upperLimit)
{
srand((unsigned)time(NULL));
return rand()%upperLimit+1;
}


感谢各位了!
...全文
79 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
wyz007134 2010-07-14
  • 打赏
  • 举报
回复
srand 放在循环中会失效
cybot7yxy 2010-07-14
  • 打赏
  • 举报
回复
问题解决了,把分给第一个了,太感谢了!
氰客 2010-07-14
  • 打赏
  • 举报
回复
学习一下~~
  • 打赏
  • 举报
回复
srand((unsigned)time(NULL));
只需要初始化一次。
因此:


#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int generateRandomNum(int upperLimit);
int main()
{
srand((unsigned)time(NULL));
for(int i=0;i<10;i++)
cout<<generateRandomNum(30)<<endl;
return 0;
}
int generateRandomNum(int upperLimit)
{
return rand()%upperLimit+1;
}



lazy_2010 2010-07-14
  • 打赏
  • 举报
回复
srand 调用一次就可以了,也不能不调用
alex_yr 2010-07-14
  • 打赏
  • 举报
回复
学习一下
tzcherish 2010-07-14
  • 打赏
  • 举报
回复
顶一楼~O(∩_∩)O~
yuhuaijun 2010-07-14
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 lightboat09 的回复:]

C/C++ code

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int generateRandomNum(int upperLimit);
int main()
{
srand((unsigned)time(NULL)); //移到这里
for(int i=0;i<1……
[/Quote]
赞一个,
LZ可以看下这个
http://blog.csdn.net/ycs0501/archive/2009/03/09/3973568.aspx
小楫轻舟 2010-07-14
  • 打赏
  • 举报
回复

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int generateRandomNum(int upperLimit);
int main()
{
srand((unsigned)time(NULL)); //移到这里
for(int i=0;i<10;i++)
cout<<generateRandomNum(30)<<endl;
return 0;
}
int generateRandomNum(int upperLimit)
{
// srand((unsigned)time(NULL)); //时间间隔太短了
return rand()%upperLimit+1;
}

64,649

社区成员

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

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