我编写了以下程序,用于删除用户输入的数组元素。
#include <stdio.h>
#include <conio.h>
void main() {
int j, i, a[100], n, key, l;
clrscr();
printf("Enter the number of elements:");
scanf("%d", &n);
printf("\nEnter the elements:\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("\nEnter the element to delete:");
scanf("%d", &key);
l = n; //Length of the array
for (i = 0; i < l; i++) {
if (a[i] == key) {
for (j = i; j < l; j++)
a[j] = a[j + 1];
l--; //Decreasing the length of the array
}
}
printf("\nThe new array is \n");
for (i = 0; i < l; i++)
printf("%d ", a[i]);
getch();
}
大部分输入都能正常工作,但当输入类似于:1 2 2 3 5
(这里2
连续重复)并且要删除的元素是2
时,输出结果为1 2 3 5
。
我该如何修改程序以删除所有输入元素的实例?