免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1637 | 回复: 4
打印 上一主题 下一主题

c++随机数问题,请指导! [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-03-02 19:39 |只看该作者 |倒序浏览
今天刚学随机数,指导怎么随机生成整数,但很好奇如何生成浮点数,但书上没写,就想了个简单方法,如代码:
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
void sort(int [],int);
void main()
{
        int a[100],b[100];
        float c[100];
        srand(time(0));
        for(int i=0;i<100;i++)
        {a[i]=rand()%100;
                cout<<a[i]<<"   ";
         b[i]=rand()%100;
                 cout<<b[i]<<endl;
         c[i]=(float)(a[i]/b[i]);
         cout<<c[i]<<endl;
        }
}
编译可以通过,但运行就弹出错误框,这是为什么呢?
于是稍作修改,变成下面:
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
void sort(int [],int);
void main()
{
        int a[100],b[100];
        float c[100];
        srand(time(0));
        for(int i=0;i<100;i++)
        {a[i]=rand()%100;
                cout<<a[i]<<"   ";
         b[i]=rand()%100;
                 cout<<b[i]<<endl;
        }
        c[i]=(float)(a[i]/b[i]);
        for(i=0;i<100;i++)
         cout<<c[i]<<endl;
}       
用着次没错误显示,但c[i]显示的数值全部一样,我用另一个编译器(c++程序学习系统)却能完成我的目标,这是为什么呢?
如果有更简单的随机浮点数的方法,请赐教!

论坛徽章:
0
2 [报告]
发表于 2010-03-02 19:49 |只看该作者
a[i]=rand()%100;
                cout<<a[i]<<"   ";
         b[i]=rand()%100;
                 cout<<b[i]<<endl;
这两个用的同一个种子,产生的随机数是一样的,
      for(i=0;i<100;i++)
         cout<<c[i]<<endl;

应该输出都是1

论坛徽章:
0
3 [报告]
发表于 2010-03-02 19:57 |只看该作者
haha,
当然是一样的了,
因为你只计算了一次啊,
第一个应该没什么问题啊
顺便问下,你用srand(time(0)),好像什么也没做啊

论坛徽章:
0
4 [报告]
发表于 2010-03-02 20:45 |只看该作者
本帖最后由 drangon 于 2010-03-02 20:47 编辑

有个问题: c=(float)(a/b);,应该写成
c = (float)a / (float)b;

另外rand()本来产生的就不是随机数,是“伪随机数”,通过数学公式计算出来的,有某些特性不奇怪。

论坛徽章:
0
5 [报告]
发表于 2010-03-02 21:02 |只看该作者
这样修改就可以了
  1. #include <iostream.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. void sort(int [],int);
  5. void main()
  6. {
  7.         int a[100],b[100];
  8.         float c[100];
  9.         srand(time(0));
  10.         for(int i=0;i<100;i++)
  11.         {a[i]=rand()%100;
  12.                 cout<<a[i]<<"   ";
  13.          
  14.          srand(time(0) + 1);//保证种子不一样
  15.          b[i]=rand()%100;
  16.                  cout<<b[i]<<endl;
  17.         }
  18.         c[i]=(float)(a[i]/b[i]);
  19.         for(i=0;i<100;i++)
  20.          cout<<c[i]<<endl;
  21. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP