[英]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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.