生成特定的随机数

Generate specific random number

我正在尝试创建一种从特定数字选择中生成随机数的方法,它必须是 0、90、180 或 270。

这是目前为止我在一定范围内生成随机数的方法,但我不确定如何从特定选择中生成随机数。

int randomNum(int min, int max) {
    return rand() % max + min;
}

嗯,我认为您正在尝试选择数组或所谓的选项列表中的特定数字,我在这里为您提供了一个简单的示例。您可以只创建一个包含所有选项的数组,并将此方法设为 return 来自给定数组的值。

#include <iostream>
#include <stdlib.h>
#include <time.h>

int main ()
{
  srand ( time(NULL) ); //initialize the random seed
  

  const char arrayNum[4] = {'1', '3', '7', '9'};
  int RandIndex = rand() % 4; //generates a random number between 0 and 3
  cout << arrayNum[RandIndex];
}

更多详情 - http://www.cplusplus.com/forum/beginner/26611/