生成随机整数从最小至最大?

编程入门 行业动态 更新时间:2024-10-12 03:16:38
本文介绍了生成随机整数从最小至最大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我要生成一个随机整数是:

  • 在区间[最小,最大] 包括
  • 的范围可以是[5,20],[-29,-3]或[-13,13](它可以在任何范围内,正或负或之间)的
  • 的code采用的是Android做工精细
  • 我走到这一步,是这样的,但似乎不负范围的工作!

    1 +(INT)(的Math.random()*((最大值 - 最小值)+ 1));

    解决方案

    我是pretty确定要将

    敏+(INT)(的Math.random()*((最大值 - 最小值)+ 1));

    不过,我要指出的范围[-3,-29]有它的最小和最大逆转。 (而且具有相同的[5,1 -13]作为通过Merlyn指出)。

    如果你想只是把任意两个号码的范围,a和b然后使用code

    诠释最小= Math.min(A,B);INT最大= Math.max(A,B);

    这样,你将不必担心秩序。这甚至会为一个== b工作。

    I want to generate a random Integer that is:

  • Inside the range [Min, Max] inclusive
  • The range can be [5,20], [-29, -3] or [-13, 13] (It can be in any range, positive or negative or in between)
  • The code is working fine in Android
  • What I got so far is this, but it seems not working with negative ranges !

    1 + (int)(Math.random() * ((Max - Min) + 1));

    解决方案

    I'm pretty sure you want

    Min+(int)(Math.random()*((Max-Min) + 1));

    However, I should point out that the range [-3,-29] has its min and max reversed. (And the same with [5,-13] as was pointed out by Merlyn.)

    If you want to just put in any two numbers for the range, a and b then use the code

    int Min = Math.min(a,b); int Max = Math.max(a,b);

    That way you won't have to worry about the order. This will even work for a==b.

    更多推荐

    生成随机整数从最小至最大?

    本文发布于:2023-11-30 09:41:28,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1649534.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:整数   最小

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!