所以我有另一个任务,它让我很难过。我必须设置功能,以便教授可以一起测试它们。他将删除我的主要功能并创建自己的功能,因此他让我们设置功能。</ p>
这些是初始化的说明:
void InitializeArray(int a[], int arraySize);
// a: the array that you want to initialize
// arraySize: The number of elements to put in the array
// returns: nothing
这是我到目前为止,任何帮助将不胜感激!
int main()
{
const int ARRAY_SIZE = 10;
int a[ARRAY_SIZE];
InitializeArray(a, ARRAY_SIZE); // This is to test my functions,
std::cout << "Initial Array= "; // InitializeArray and printArray.
PrintArray(a, ARRAY_SIZE);
}
void SeedRand(int x)
{
srand(x); // Seed the random number generator
}
void InitializeArray(int a[], int arraySize)
{
arraySize = 10;
a[arraySize] = { 1 + rand() % 100 };
for (int i = 0; i < arraySize; i++)
// Develop an algorithm that inserts random numbers
// between 1 and 100 into a[]
// hint: use rand()
}
void PrintArray(int a[], int arraySize)
{
for (int n = 0; n < arraySize; ++n)
{
std::cout << a[n] << " ";
}
// print the array using cout
// leave 1 space in-between each integer
// Example: if the array holds { 1, 2, 3 }
// This function should print: 1 2 3
// It is ok to have a dangling space at the end
}
答案 0 :(得分:3)
这段代码很奇怪
void InitializeArray(int a[], int arraySize)
{
arraySize = 10;
a[arraySize] = { 1 + rand() % 100 };
for (int i = 0; i < arraySize; i++)
arraySize设置在函数外面,但你在里面分配10,为什么?为函数提供大小的关键是函数知道大小。
初始化数组时,需要遍历每个元素并为其赋值(使用错误的语法)
a[arraySize] = { 1 + rand() % 100 };
您实际上正在访问数组外部的元素,有效索引为0..arraySize-1
。
所以要初始化每个元素写这样的东西
for (int i = 0; i < arraySize; ++i)
{
a[i] = 1 + rand()% 100;
}