c - 如何在另一个数组中的用户指定位置插入一个数组并获取结果数组?
问题描述
在指定位置插入第二个数组后将结果数组向右移动时会出现问题。请注意不需要旋转、循环或反向。
#include <stdio.h>
void main() {
int i, n, m, location, b[20], a[20];
printf("Enter the number of elements in first array:\n");
scanf("%d", &m);
printf("Enter the elements of first array : \n");
for (i = 0; i < m; i++) {
scanf("%d", &a[i]);
}
printf("Enter the location to insert second array : \n");
scanf("%d", &location);
printf("Enter the number of elements in second array :\n");
scanf("%d", &n);
printf("Enter the elements of second array : \n");
for (i = 0; i < n; i++) {
scanf("%d", &b[i]);
}
for (i = m; i >= location; i--) {
a[i + n] = a[i];
}
a[location + i] = b[i];
m++;
printf("Resulting array after insertion is : \n");
for (i = 0; i < m; i++) {
printf("%d ", a[i]);
}
printf("\n");
}
运行程序后。我明白这是不正确的。
Enter the number of elements in first array:
3
Enter the elements of first array :
10 20 30
Enter the location to insert second array :
1
Enter the number of elements in second array :
2
Enter the elements of second array :
55 66
Resulting array after insertion is :
10 55 30 20
解决方案
您只是添加b
to的一个元素a
更换你的
a[location+i] = b[i];
m++;
和
for(i=0;i<n;i++)
{
a[location+i] = b[i];
}
m+=n;
因为您需要遍历b
数组才能将所有元素添加到a
数组中。
推荐阅读
- wordpress - 使用借记卡或信用卡支付的 Woocommerce Paypal Pay 间歇性不显示
- reactjs - 在本地主机上运行生产构建时出现路由问题
- ios - 使用 callkit 接听电话后如何打开 in Call UI
- python - Django Rest Framework,配置不正确的查找字段
- c# - 使用另一个列表中的详细信息填充大量对象
- java - Using validation in Spring to restrict ZonedDateTime field to 3 digits at millisecond time
- azure - Azure 消费 API
- java - 如何使用equals从firebase中检索
- ios - 如何在 Swift 中更改按钮的大小?
- typescript - Vue 基于类的组件扩展和混合