【发布时间】:2018-02-27 09:25:31
【问题描述】:
我有一个非常简单的问题。我对这个简短程序的目标是让它显示一组数字(这是硬编码的),然后让用户指定应该从哪个索引中删除数组的数字。然后它输出新数组。该程序有效,但有一个重大错误。例如,当我运行它并选择位置 2 时,它应该删除 45,而不是删除 34。程序输出:
12 45 2 8 10 16 180 182 22
而不是: 12 34 2 8 10 16 180 182 22
请注意,如果您还记得列表从 0 开始,我想要删除的数字位置改为在我实际想要删除的数字之前的位置删除。谢谢!
//This program demos basic arrays
#include <iostream>
using namespace std;
const int CAP = 10;
int main()
{
//read index from user, delete number in position of index they specify.
//when printing the list, number should be gone.
int size;
int list[CAP] = { 12, 34, 45, 2, 8, 10, 16, 180, 182, 22 };
size = 10;
int i, delIndex;
cout << "Your list is: " << endl;
for (i = 0; i < CAP; i++)
{
cout << list[i] << endl;
}
cout << "\nPlease enter index to delete from: ";
cin >> delIndex;
for (i = delIndex; i <= 10; i++)
{
list[i - 1] = list[i];
}
cout << "The index position you specified has been deleted." << endl;
cout << "The new array is: " << endl;
for (i = 0; i < (size - 1); i++)
{
cout << list[i] << endl;
}
return 0;
}
【问题讨论】:
-
您的代码将所有元素从您输入的索引复制到其左侧的元素。索引 0 为 12,索引 1:34,索引 2:45。您的复制操作将索引 2 复制到位置 2-1(复制 45 到 34)。
-
尝试 list[i] = list[i+1] with i
-
你知道我会怎么解决这个问题吗?多年来,我一直在搞乱第二个 for 语句,但由于我是 c++ 新手,所以我无法弄清楚...
-
迈克尔你刚刚告诉我的修复了它!非常感谢。