简体   繁体   English

如何创建从0缩放到用户输入的数组

[英]How to create an array to scale from 0 until user input

I am trying to create a program that prints out an array based on user input. 我正在尝试创建一个程序,该程序根据用户输入打印出一个数组。 The array needs to start from 0 and scale to the number enter by user. 数组需要从0开始,并缩放到用户输入的数字。 So if user inputs 5 the the array values will be [0][1][2][3][4][5]. 因此,如果用户输入5,则数组值将为[0] [1] [2] [3] [4] [5]。 For some reason my code just prints out 0. 由于某种原因,我的代码仅打印出0。

#include <iostream>
using namespace std;

int main() {
cout << "Enter the value of n: ";
int n;
cin >> n;
int *arr1 = new int[n];

for(int i = 0; i < n; i ++){
    arr1[i] = 0;

}
cout << *arr1 << endl;

delete [] arr1;
return 0;
}

There are few bugs in your code. 您的代码中几乎没有错误。

You expect the output to be [0][1][2][3][4][5] when the n = 5. Therefore your output has (n + 1) elements. 当n = 5时,您期望输出为[0] [1] [2] [3] [4] [5] 。因此,您的输出具有(n + 1)个元素。 So your array should also have (n + 1) elements. 因此,您的数组还应该具有(n + 1)个元素。

int *arr1 = new int[n + 1];

In your code you assign 0 to each element in your array. 在代码中,将0分配给数组中的每个元素。 But you expect the array to contain 0, 1, 2, .., n 但您希望数组包含0、1、2,..,n

for(int i = 0; i < n + 1; i++){
  arr1[i] = i;
}

In your code, you only print the first element. 在您的代码中,您仅打印第一个元素。 *arr1 is same as arr1[0]. * arr1与arr1 [0]相同。 So another for loop is required to print the each element in your array. 因此,需要另一个for循环来打印数组中的每个元素。

for(int i = 0; i < n + 1; i++){
  cout << "[" << arr1[i] << "]" << endl;
}

Then you will get the output [0][1][2][3][4][5] when the n = 5 然后,当n = 5时,将获得输出[0] [1] [2] [3] [4] [5]

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

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