【问题标题】:Generate specific random number生成特定的随机数
【发布时间】:2021-08-16 02:48:16
【问题描述】:

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

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

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

【问题讨论】:

  • 生成一个 0 到 3 之间的数,然后乘以 90

标签: c++ visual-c++


【解决方案1】:

嗯,所以我认为您正在尝试在数组或所谓的选项列表中选择特定数字,我在这里为您提供了一个快速示例。你可以创建一个包含所有选项的数组,并让这个方法从给定的数组中返回一个值。

#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/

【讨论】:

猜你喜欢
  • 2016-05-04
  • 2021-05-31
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
相关资源
最近更新 更多