【问题标题】:How do I input random numbers in C++ array?如何在 C++ 数组中输入随机数?
【发布时间】:2022-01-12 16:59:49
【问题描述】:
#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 函数为我的数组提供从 -100 到 100 的随机值,但我不知道如何将该 rand 函数放入数组中,以便我的数组可以在其中生成随机数,希望这有意义我该怎么做这样做?

【问题讨论】:

  • 您需要在循环中进行。
  • 只播种一次,并且更喜欢&lt;random&gt; 设施而不是srand/rand
  • 考虑使用std::generate,例如std::generate(begin(myArray), end(myArray), randBetween);
  • 一般建议:一次做/学习一件事。你知道如何给数组元素赋值吗?你知道如何生成随机数吗? (你的代码没有正确地做到这一点)只有当你得到它们中的每一个时,你才应该把它们放在一起

标签: c++ arrays function


【解决方案1】:

将 cmets 汇总为答案:

你可以使用循环:

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

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

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

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

不过,你有一个大问题。 You should not call srand each time you want a random number。在main 的开头调用它一次。正如您现在所拥有的那样,您可能会在给定运行中用一个数字填充数组。如果当前时间的第二个在程序运行期间发生变化,则数字在数组中的一部分发生变化的可能性很小。

另外C++ Standard Library for random numbersrand 更可取。我建议使用 a standard container 而不是原生数组。

【讨论】:

  • 谢谢,这很有帮助!
  • 如果您还展示了使用标准库功能生成随机数的标准方法会更好。
  • @digito_evo:我宁愿把我的回答集中在被问到的问题上。 rand 有效,但并不理想,而且我链接的内容中有很好的示例代码。
【解决方案2】:

另一种方法是使用 PRNG(伪随机数生成器)。这是来自包含随机、包含功能的标头。像这样,在 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

【讨论】:

  • 这不是好的代码。每次函数启动时都会实例化您的 PRNG。 PRNG 需要保持其状态。从外观上看,他们也想要整数;根本没有理由使用std::uniform_real_distribution
【解决方案3】:

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

#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 风格的约定。事实上,你甚至不需要一个函数。

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

#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';
}

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

#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 可以提供多个分布。

我得到的一个输出:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 2017-09-02
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 2018-11-19
    相关资源
    最近更新 更多