繁体   English   中英

如何在 C++ 数组中输入随机数?

[英]How do I input random numbers in C++ array?

#include <iostream>
#include <ctime>


using namespace std;
int randBetween()
{
    
    unsigned seed = time(0);
    srand(seed);
    
    const int MIN_VALUE = -100;
    const int MAX_VALUE = 100;
    
    return (rand() % (MAX_VALUE - MIN_VALUE + 1 )) + MIN_VALUE;
}




int main() {
   
    const int SIZE = 10;
    
    int myArray[SIZE];
    
    
    // ^^ how do I use function above to give myArray random values?
    
    return 0;
}

我想使用该 rand function 为我的数组提供从 -100 到 100 的随机值,但我不知道如何将 rand function 放入数组中,以便我的数组可以在其中生成随机数,希望这有意义我该怎么做?

首先,我们将查看您的代码并对其进行批评。

#include <iostream>
#include <ctime>
// MISSING <cstdlib> for C random functions

using namespace std;  // Bad Practice
int randBetween()
{
    
    unsigned seed = time(0);  // Wrong placement; should only instantiate ONCE
    srand(seed);
    
    const int MIN_VALUE = -100;
    const int MAX_VALUE = 100;
    
    return (rand() % (MAX_VALUE - MIN_VALUE + 1 )) + MIN_VALUE;
    // Modulo math tends to make the values in the lower end of the range more prevalent; i.e., 
    // it's not very uniform.
}




int main() {
   
    const int SIZE = 10;  // All caps names for constants is not desirable; they can be confused for macros
    
    int myArray[SIZE];  // Prefer std::array if the size is known, else std::vector for most cases
    
    
    // ^^ how do I use function above to give myArray random values?
    
    return 0;
}

当 C++ 提供更好的方法时,最大的问题是使用 C 风格的约定。 事实上,您甚至不需要 function。

将随机数放入数组的秘诀是循环。 让您的循环访问每个元素并分配一个新的随机数。 可以直接使用,如我的第一个示例,也可以使用 function (如我的第二个示例)。

#include <array>
#include <iostream>
#include <random>

int main() {
  const int minValue = -100;
  const int maxValue = 100;
  const int size = 10;

  std::array<int, size> myArray;

  // std::mt19937 is the goto PRNG in <random>
  // This declaration also seeds the PRNG using std::random_device
  // A std::uniform_int_distribution is exactly what it sounds like
  // Every number in the range is equally likely to occur.
  std::mt19937 prng(std::random_device{}());
  std::uniform_int_distribution<int> dist(minValue, maxValue);

  for (auto& i : myArray) {
    i = dist(prng);
  }

  for (auto i : myArray) {
    std::cout << i << ' ';
  }
  std::cout << '\n';
}

现在,如果您想要或需要 function,还需要做一些额外的工作。

#include <array>
#include <iostream>
#include <random>

int randBetween() {
  const int minValue = -100;
  const int maxValue = 100;

  // The keyword static is required now so that the PRNG and distribution
  // are not re-instantiated every time the function is called. This is
  // important for them both to work as intended. Re-instantiating resets
  // their state, and they constantly start from scratch. They must be allowed
  // to persist their state for better results.
  static std::mt19937 prng(std::random_device{}());  // Note the static
  static std::uniform_int_distribution<int> dist(minValue, maxValue);

  return dist(prng);
}

int main() {
  const int size = 10;

  std::array<int, size> myArray;
  for (auto& i : myArray) {
    i = randBetween();
  }

  for (auto i : myArray) {
    std::cout << i << ' ';
  }
  std::cout << '\n';
}

将 PRNG 与分发分开是一种很好的做法,尤其是当程序变得更大时。 然后,如果需要,您的单个 PRNG 可以提供多个分布。

我得到的一个 output:

-2 -37 81 85 -38 -62 31 -15 -12 -31

将评论汇总为答案:

你可以使用一个循环:

for (size_t i = 0; i < SIZE; ++i)
{
    myArray[i] = randBetween();
}

或者您可以使用标准算法std::generate

std::generate(std::begin(myArray), std::end(myArray), randBetween);

这将遍历数组,为每个成员调用randBetween并将其分配给结果。

但是,你有一个大问题。 您不应该在每次需要随机数时调用srand 调用一次,在main的开头。 正如您现在所拥有的那样,您可能会在给定的运行中用一个数字填充数组。 如果当前时间的第二个在程序运行期间发生变化,则数字在数组中的一部分发生变化的可能性很小。

此外,随机数的 C++ 标准库rand更可取。 而且我建议使用标准容器而不是本机数组。

另一种方法是使用 PRNG(伪随机数生成器)。 这是来自包含随机,包含功能 header。 像这样,在 C++17 编译器中运行:

#include <iostream>
#include <random>
#include <functional> // For std::bind()


auto createUniformPseudoRandomNumberGenerator(double max)
{
 std::random_device seeder; 
 std::default_random_engine generator{seeder()};
 std::uniform_real_distribution distribution{0.0, max};
 return std::bind(distribution, generator); 
}

int main() 
{

const int SIZE = 10;

int myArray[SIZE];


double limit{};
std::cout<<"Enter max number limit.\n";
std::cin>>limit;

static auto random_number=createUniformPseudoRandomNumberGenerator(limit);

for (size_t i{};i<SIZE;++i)
{
    myArray[i]=  random_number();
}


return 0;
}

链接: https://onlinegdb.com/686M8KB1p

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM