簡單的任務,生成我想要的長度的陣列。
我也不知道如何獲取我創建的陣列,除了我自己的奇怪方法。我的代碼的第一部分是否正常作業,我應該重新考慮我想要獲取它們的方式(可選)?
雖然,我確實理解為什么我每次都得到相同的值,但我不認為,這與我的問題有某種關系。
我正在寫下這個:
cin >> x;
int array1[x];
int array2[x];
for (int i = 0; i <= x; i ) {
array1[i] = rand() % 10 1;
array2[i] = rand() % 10 1;
}
cout << "[" << array1[a];
for (int a = 0; a <= x; a ) {
a = 1;
cout << ", " <<array1[a];
}
cout << "] [" << array2[b];
for (int b = 0; b <= x; b ) {
b = 1;
cout << ", " << array2[b];
}
cout << "]";
為什么我在 x = 6、5、15 的情況下會得到一些例外的答案,如下所示:
[2, 5, 9, 6, 0] [8, 1, 9, 6, 32759]
[2, 5, 9, 6, 2, 8, 3, 2, 8] [8, 1, 9, 6, 2, 7, 4, 7, 7]
uj5u.com熱心網友回復:
或者使用標頭和 std::vector、std::generate(無原始回圈)。此外,當您撰寫代碼時,請撰寫小的可讀函式。為了獲得唯一的亂數,需要為隨機生成器播種。
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>
int generate_random_number()
{
// only initialize the generator and distribution once (static)
// and initialize the generator from a random source (device)
static std::mt19937 generator(std::random_device{}());
static std::uniform_int_distribution<int> distribution{ 1,10 };
return distribution(generator);
}
// overload stream output for vector, so we can use vectors in std::cout
std::ostream& operator<<(std::ostream& os, const std::vector<int>& values)
{
bool comma{ false };
os << "[";
for (const int value : values)
{
if (comma) os << ", ";
os << value;
comma = true;
}
os << "]";
return os;
}
// helper function to create an array of given size
std::vector<int> create_random_array(const std::size_t size)
{
std::vector<int> values(size); // create and allocate memory for an array of size ints
std::generate(values.begin(), values.end(), generate_random_number); // fill each value in the array with a value from the function call to generate_random_number
return values;
}
int main()
{
std::size_t count;
std::cout << "how many random numbers ? : ";
std::cin >> count;
auto array1 = create_random_array(count);
std::cout << array1 << "\n";
auto array2 = create_random_array(count);
std::cout << array2 << "\n";
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535324.html
標籤:C 数组
