黑马程序员技术交流社区

标题: 为什么会有0的输出....不解.....求解答 [打印本页]

作者: 黄金龙    时间: 2013-1-27 23:56
标题: 为什么会有0的输出....不解.....求解答
本帖最后由 黄金龙 于 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

作者: jonn    时间: 2013-1-28 00:01
改成这样 int x =(int)(Math.random()*10+1);
               
作者: 黄金龙    时间: 2013-1-28 00:02
赵文 发表于 2013-1-28 00:01
改成这样 int x =(int)(Math.random()*10+1);

这样会出10......所以呢.....也不是我的需求我就是 要1-9
作者: 王溢君    时间: 2013-1-28 00:03
Math.random()这个方法是包含0,不包含10的随机数。。。

所以我们把它+1就可以得到解决了。
作者: jonn    时间: 2013-1-28 00:04
(int)Math.random()*9+1
作者: 黄金龙    时间: 2013-1-28 00:06
luck28 发表于 2013-1-28 00:03
Math.random()这个方法是包含0,不包含10的随机数。。。

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

加1会出10的 我就是要1-9
作者: 黑马刘向阳    时间: 2013-1-28 00:17
  1.     public static int mathRandom()
  2.     {        

  3.             int x =(int)(Math.random()*10);
  4.             if(x<=0)
  5.                   x = mathRandom();
  6.             return x;               
  7.     }
复制代码
改成这样
作者: 邝雄伟    时间: 2013-1-28 01:16
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.        }


作者: 黄鸿达    时间: 2013-1-28 04:55
    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也可以。

作者: 黄金龙    时间: 2013-1-29 12:41
本帖最后由 黄金龙 于 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 就会返回给最开始调用那




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2