A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 黄金龙 中级黑马   /  2013-1-27 23:56  /  2131 人查看  /  10 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 黄金龙 于 2013-1-29 12:45 编辑
  1.         public static int mathRandom()
  2.         {        

  3.                 int x =(int)(Math.random()*10);
  4.                 if(x<=0)
  5.                         mathRandom();//这里改成x=mathRandom();就不会出错了......就能实现返回1-9的随机数字....
  6.                 return x;               
  7.         }
复制代码
为什么会有0的输出....不解.....求解答
.需求我就要1-9的随机数

原因是   递归调用mathRandom();返回的值没赋给x 所以就继续执行下去x=0 就会返回给最开始调用那

未命名.jpg (5.44 KB, 下载次数: 33)

未命名.jpg

10 个回复

倒序浏览
改成这样 int x =(int)(Math.random()*10+1);
               
回复 使用道具 举报
赵文 发表于 2013-1-28 00:01
改成这样 int x =(int)(Math.random()*10+1);

这样会出10......所以呢.....也不是我的需求我就是 要1-9
回复 使用道具 举报
Math.random()这个方法是包含0,不包含10的随机数。。。

所以我们把它+1就可以得到解决了。
回复 使用道具 举报
(int)Math.random()*9+1

评分

参与人数 1黑马币 +15 收起 理由
舒远 + 15

查看全部评分

回复 使用道具 举报
luck28 发表于 2013-1-28 00:03
Math.random()这个方法是包含0,不包含10的随机数。。。

所以我们把它+1就可以得到解决了。 ...

加1会出10的 我就是要1-9
回复 使用道具 举报
  1.     public static int mathRandom()
  2.     {        

  3.             int x =(int)(Math.random()*10);
  4.             if(x<=0)
  5.                   x = mathRandom();
  6.             return x;               
  7.     }
复制代码
改成这样
回复 使用道具 举报
public static int mathRandom()

02.        {        

03.

04.                int x =(int)(Math.random()*9+1);    //改成这样,就可以获得1到9的随机数

05.                if(x<=0)

06.                        mathRandom();

07.                return x;               

08.        }

评分

参与人数 1黑马币 +15 收起 理由
舒远 + 15

查看全部评分

回复 使用道具 举报
    public static int mathRandom()
    {        
            int x =(int)(Math.random()*10);
            if(x==0)
                  x = mathRandom();
            return x;               
    }

---------------------------------------------------------------------------------------

    public static int mathRandom()
    {        
      int a=0;
      
            while(a==0){
             int x=(int)(Math.random()*10);
             a=x;
            }
            return a;               
    }

下面那个自己写的 上面看别人if(x<=0)觉得奇怪,Math.random返回的是正数,所以实验改成x==0也可以。

评分

参与人数 1黑马币 +15 收起 理由
舒远 + 15 这个思路也不错。

查看全部评分

回复 使用道具 举报
本帖最后由 黄金龙 于 2013-1-29 12:43 编辑
terrynzh 发表于 2013-1-28 01:22
因Math类的random方法是返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。有可能返回0.0,而0.0转换成 ...


这不是原因     原因是   递归调用mathRandom();返回的值没赋给x 所以就继续执行下去x=0 就会返回给最开始调用那
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马