gpt4 book ai didi

C++ 在索引删除硬编码数字列表中的位置

转载 作者:行者123 更新时间:2023-11-28 04:47:22 24 4
gpt4 key购买 nike

我有一个非常简单的问题。我对这个短程序的目标是让它显示一组数字(这是硬编码的),然后让用户指定应该从哪个索引中删除数组中的数字。然后它输出新数组。该程序可以运行,但有一个重大错误。例如,当我运行它并选择位置 2 时,应该删除 45,而不是删除 34。程序输出:

12452个8个101618018222

而不是:12342个8个101618018222

请注意,如果您还记得列表是从 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;
}

最佳答案

替换这个:

for (i = delIndex; i <= 10; i++)
{
list[i - 1] = list[i];
}

有了那个:

for (i = delIndex; i < size-1; i++)
{
list[i] = list[i+1];
}

关于C++ 在索引删除硬编码数字列表中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49005190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com