简体   繁体   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;
}

I wanna use that rand function to give my array random values from -100 to 100 but I dont know how to put that rand function in the array so that my array can generate random number inside it hopefully that makes sense how do I do that?我想使用该 rand function 为我的数组提供从 -100 到 100 的随机值,但我不知道如何将 rand function 放入数组中,以便我的数组可以在其中生成随机数,希望这有意义我该怎么做?

First we'll take a look at your code and critique it.首先,我们将查看您的代码并对其进行批评。

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

The biggest issue is the use of C-style conventions when C++ provides better methods.当 C++ 提供更好的方法时,最大的问题是使用 C 风格的约定。 In fact, you won't even need a function for this.事实上,您甚至不需要 function。

The secret sauce of getting the random numbers into your array is a loop.将随机数放入数组的秘诀是循环。 Make your loop visit every element and assign a new random number.让您的循环访问每个元素并分配一个新的随机数。 Either directly, as in my first example, or by using a function as in my second example.可以直接使用,如我的第一个示例,也可以使用 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';
}

Now, if you want or need the function, there's a little bit of extra work that needs to be done.现在,如果您想要或需要 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';
}

Separating the PRNG from the distribution is good practice, especially when programs get larger.将 PRNG 与分发分开是一种很好的做法,尤其是当程序变得更大时。 Then your single PRNG can feed multiple distributions if needed.然后,如果需要,您的单个 PRNG 可以提供多个分布。

One output that I got:我得到的一个 output:

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

Rolling up the comments into an answer:将评论汇总为答案:

You could use a loop:你可以使用一个循环:

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

Or you could use the standard algorithm std::generate :或者您可以使用标准算法std::generate

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

This will loop over the array, calling randBetween for each member and assigning it to the result.这将遍历数组,为每个成员调用randBetween并将其分配给结果。

You have a big issue, however.但是,你有一个大问题。 You should not call srand each time you want a random number .您不应该在每次需要随机数时调用srand Call it once , in the beginning of main .调用一次,在main的开头。 As you have it now, you will likely fill the array with one number for a given run.正如您现在所拥有的那样,您可能会在给定的运行中用一个数字填充数组。 There is a tiny chance the number will change part way through the array if the second of the current time changes during the program run.如果当前时间的第二个在程序运行期间发生变化,则数字在数组中的一部分发生变化的可能性很小。

Also the C++ Standard Library for random numbers is much preferable to rand .此外,随机数的 C++ 标准库rand更可取。 And I'd recommend using a standard container rather than a native array.而且我建议使用标准容器而不是本机数组。

An alternate way would be to use PRNG(Pseudo Random Number Generator).另一种方法是使用 PRNG(伪随机数生成器)。 This is from the include random, include functional header.这是来自包含随机,包含功能 header。 Like this, run this in C++17 compiler:像这样,在 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;
}

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

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

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