【问题标题】:How to store integers in an array and display them in C++ language? [duplicate]如何将整数存储在数组中并用 C++ 语言显示? [复制]
【发布时间】:2022-11-15 19:11:17
【问题描述】:
#include <iostream>

using namespace std;

int main() {
  int marks[1000], i, j;
  cout << "Enter the size of an array: ";
  cin >> i;
  for (j = 0; j <= i; j++) {
    cout << "Enter " << i << " element of array: ";
    cin >> marks[i];
    i++;
  }
  for (j = 0; j <= i; j++) {
    cout << "The " << i << " element of array is: " << endl;
    i++;
  }
  return 0;
}

我最初声明了一个整数数组以及ij 变量。然后我询问用户数组的大小,然后将其分配给i 变量。然后i初始化了一个for循环,让用户输入一个数组的元素,并存储到数组的i中。我想我在 for 循环中犯了一些错误,所以你们能帮我解决这个问题吗?

【问题讨论】:

标签: c++ arrays


【解决方案1】:

您缺少元素的实际打印。此外,在循环中,您不需要增加数组的大小:

    for ( j = 0; j <= i; j++)
    {
        cout<<"Enter "<<i<<" element of array: ";
        cin>>marks[i];
    }

    for ( j = 0; j <= i; j++)
    {
        cout<<"The "<<j<<" element of array is: "<<marks[j]<<endl;
    }

建议为变量使用更具描述性的名称(例如elemCount),以避免此类错误。

【讨论】:

  • 对于第一个循环中的coutcin,您应该使用j 而不是i。另外,我认为循环条件应该使用&lt;而不是&lt;=,但这只能由OP澄清。
猜你喜欢
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
  • 2017-08-14
  • 1970-01-01
相关资源
最近更新 更多