显示用户创建的数组中的数字
Displaying numbers from a user created array c++
好吧,这可能是一个非常简单的问题,我只是很新的c++和努力理解大多数东西。我被要求创建一个存储随机数的数组,但用户要定义数组的大小。然后我必须显示数组中的所有数字。我正在努力显示数组的所有元素。目前,我很确定我已经得到了数组部分,但我似乎只能显示一个数字。下面是我到目前为止的代码:
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <ctime>
using namespace std;
using std::srand;
using std::rand;
using std::time;
void Display(int *, int);
int main(void)
{
int userSize;
cout << "Please enter the size of the array: ";
cin >> userSize;
int* randArray = new int[userSize];
srand(time(NULL));
for (int i = 0; i < userSize; i++) {
randArray[i] = rand() % 20 + 1;
}
//Disregard the next few lines, I was just testing to see if anything was actually in the array.
/*cout << randArray[0] << endl;
cout << randArray[1] << endl;
cout << randArray[2] << endl;
cout << randArray[19] << endl;*/
Display(randArray, sizeof(randArray) / sizeof(int));
return 0;
delete[] randArray;
}
void Display(int *arrayData, int numElements)
{
for (int counter = 0; counter < numElements; counter++)
{
std::cout << *(arrayData + counter) << std::endl;
}
return;
}
我还应该提到,老师提供给我们的代码后面的行删除数组。
这是我必须回答的问题:询问用户要在数组中存储的元素数量。然后,您应该动态分配内存来保存该数组,该数组将以与前一个任务相同的方式继续使用(用随机数据填充数组,将数据显示给屏幕)。
sizeof(randArray)
没有告诉您已分配的字节数。相反,它告诉您指针的大小,在您的系统中,它恰好与整数的大小相同,因此sizeof(randArray) / sizeof(int)
总是返回1。相反,使用userSize
作为Display
函数调用中的第二个参数。
同样,return 0
之后是delete[] randArray
。这是不正确的;return 0
之后不会执行任何操作。你想把它放在上面。
进一步,考虑使用std::vector
来代替(除非您需要为这个赋值使用一个原始指针)
问题是sizeof
。它给出了参数类型的大小,而不是后面的内容。您应该将userSize
传递给Display()
。
你也应该在return
之前delete
数组。return
后面的代码永远不会被执行。
相关文章:
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 数组/c++中的大量数字
- 遍历并行数组以确定C++中的最大数字
- 整数区间(或 int 数组)中每个数字的出现次数
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 获取 2D 数组 c++ 中的所有数字对
- 为什么使用数组元素查找最大数字的程序不起作用?
- 如何从向量或数组中选择最常见的数字?(前五名)C++
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 以十为基数的数字到布尔数组,该数组要求二进制/基数为 2 的数字
- C++ 检查结果数组中有多少次数字
- 如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
- 如何在C++中有效地将数字值重新分配给字符数组
- 查找数组中的最小数字
- 查找数组中重复(重复)数字的索引
- 我必须找到给定数组中所有数字的周期,就像有很多解决方案,但数组的大小是 10^5
- 类、数字/数组或对象中的对象