簡體   English   中英

如何創建從0縮放到用戶輸入的數組

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

我正在嘗試創建一個程序,該程序根據用戶輸入打印出一個數組。 數組需要從0開始,並縮放到用戶輸入的數字。 因此,如果用戶輸入5,則數組值將為[0] [1] [2] [3] [4] [5]。 由於某種原因,我的代碼僅打印出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;
}

您的代碼中幾乎沒有錯誤。

當n = 5時,您期望輸出為[0] [1] [2] [3] [4] [5] 。因此,您的輸出具有(n + 1)個元素。 因此,您的數組還應該具有(n + 1)個元素。

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

在代碼中,將0分配給數組中的每個元素。 但您希望數組包含0、1、2,..,n

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

在您的代碼中,您僅打印第一個元素。 * arr1與arr1 [0]相同。 因此,需要另一個for循環來打印數組中的每個元素。

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

然后,當n = 5時,將獲得輸出[0] [1] [2] [3] [4] [5]

暫無
暫無

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM