在给定范围之间生成奇数随机数 [英] Generating an Odd Random Number between a given Range

查看:235
本文介绍了在给定范围之间生成奇数随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在给定范围之间生成奇数随机数..

How to generate an odd Random number between a given range..

对于Eg:对于1到6之间的范围..
随机数是3或1或5

For Eg: For range between 1 to 6 .. Random No is 3 or 1 or 5

生成随机数的方法编号:

Method for Generating Random No :

    Random_No = Min + (int)(Math.Random()*((Max-Min)+1))

请参阅如何在Java中生成特定范围内的随机整数?

生成奇数随机数的方法编号:

Method For Generating Odd Random No :

    Random_No = Min + (int)(Math.Random()*((Max-Min)+1))
    if(Random_No%2 ==0)
    {
          if((Max%2)==0)&&Random_No==Max)
          {
              Random_No = Random_No - 1;  
          }
          else{
              Random_No = Random_No +1;
          }
    }

此函数将始终将2转换为3而不是1
我们可以把它变成一个更随机的函数,有时可以将2转换为3,有时转换成1吗?

This Function will always convert 2 into 3 and not 1 Can we make this a more random function which can convert 2 sometimes into 3 and sometimes into 1 ??

推荐答案

假设max是包含的,我建议如下:

Assuming max is inclusive, I'd suggest the following:

if (Max % 2 == 0) --Max;
if (Min % 2 == 0) ++Min;
Random_No = Min + 2*(int)(Math.random()*((Max-Min)/2+1));

它导致所有奇数之间的均匀分布。

It results in even distribution among all the odd numbers.

这篇关于在给定范围之间生成奇数随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆