#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;
}
我最初声明了一个整数数组以及i
和j
变量。然后我向用户询问数组的大小,然后将其分配给i
变量。然后i
初始化一个for循环,要求用户输入数组的元素,并将其存储在数组的i
中。我想我在for循环中犯了一些错误,你们能帮我一下吗?
您错过了元素的实际打印。此外,在循环中,您不需要增加数组的大小:
for ( j = 0; j < i; j++)
{
cout<<"Enter "<<j<<" element of array: ";
cin>>marks[j];
}
for ( j = 0; j < i; j++)
{
cout<<"The "<<j<<" element of array is: "<<marks[j]<<endl;
}
建议为变量使用更具描述性的名称(例如elemCount
),这样可以避免这类错误。