返回一个随机的偶数 [英] Returning a random even number

查看:139
本文介绍了返回一个随机的偶数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法。方法rnd,返回两个边界之间的单个随机整数:

I have the following methods. The method rnd, returns a single random integer between two bounds:

  /* Create next batch of 55 random numbers */
  void advance_random (){
int j1;
double new_random;
for(j1=0; j1<24; j1++){
  new_random = oldrand[j1]-oldrand[j1+31];
  if(new_random<0.0){
    new_random = new_random+1.0;
  }
  oldrand[j1] = new_random;
}
for(j1=24; j1<55; j1++){
  new_random = oldrand[j1]-oldrand[j1-24];
  if(new_random<0.0){
    new_random = new_random+1.0;
  }
  oldrand[j1] = new_random;
}
 } //advance_ramdom

  /* Fetch a single random number between 0.0 and 1.0 */
  double randomperc(){
jrand++;
if(jrand>=55){
  jrand = 1;
  advance_random();
}
return((double)oldrand[jrand]);
  } //randomPerc

  /* Fetch a single random integer between low and high including the bounds */
  synchronized int rnd (int low, int high){
int res;
if (low >= high){
  res = low;
} else {
  res = low + (int)(randomperc()*(high-low+1));
  if (res > high){
    res = high;
  }
}
return (res);
  } // rnd

如何修改这个以便返回的数字mod2 = 0 ?

How do I modify this so that the number returned mod2 =0?

谢谢

推荐答案

如果你能得到一个随机数范围 [a,b] 那么你所要做的就是得到一个 [(a + 1)/ 2范围内的随机数,b / 2] 并将其乘以2得到范围内的随机偶数 [a,b]

if you can get a random number in range [a, b] then all you have to do is get a random number in the range [(a+1)/2, b/2] and multiply it by 2 to get a random even number in range [a, b]

这篇关于返回一个随机的偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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