当前位置: 首页 > 面试题库 >

Returning a random even number

燕智
2023-03-14
问题内容

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

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

Thanks


问题答案:

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]



 类似资料:

相关阅读

相关文章

相关问答