当前位置:   article > 正文

C语言——四种方法将数组A中的内容和数组B中的内容进行交换(数组一样大)_将数组a中的内容和数组b中的内容进行交换。(数组一样大)

将数组a中的内容和数组b中的内容进行交换。(数组一样大)

方法一:运用逻辑运算将数组中每个元素进行交换,在使用循环将整个数组元素交换
              交换时创建第三变量来完成过程
源代码:

#include<stdio.h>
#include<stdlib.h>
int main() {
 int i, a[5], b[5], t;  //提前设定好两个数组均为5个元素
 printf("Please input the first array:");
 for (i = 0; i < 5; i++)
  scanf_s("%d", &a[i]);
 printf("Please input the second array:");
 for (i = 0; i < 5; i++)
  scanf_s("%d", &b[i]);
 for (i = 0; i < 5; i++)
 {
  t = a[i]; a[i] = b[i]; b[i] = t;  //利用第三变量t进行数组元素的交换
 }
 printf("交换后的数组:\n");
 printf("Please input the first array:");
 for (i = 0; i < 5; i++)
  printf("%d ", a[i]);
 printf("\n");
 printf("Please input the second array:");
 for (i = 0; i < 5; i++)
  printf("%d ", b[i]);
 printf("\n");
 system("pause");
 return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

方法二:利用指针函数进行交换各元素的值(需要对指针有一定的认识)
源代码:

#include<stdio.h>
#include<stdlib.h>
int main() {
 void swap(int* x, int* y);  //调用指针函数
 int i, a[5], b[5], t;   //提前设定好两个数组均为5个元素
 printf("Please input the first array:");
 for (i = 0; i < 5; i++)
  scanf_s("%d", &a[i]);
 printf("Please input the second array:");
 for (i = 0; i < 5; i++)
  scanf_s("%d", &b[i]);
 for (i = 0; i < 5; i++)
 {
  swap(&a[i], &b[i]);  //利用指针函数进行元素的交换
 }
 printf("交换后的数组:\n");
 printf("Please input the first array:");
 for (i = 0; i < 5; i++)
  printf("%d ", a[i]);
 printf("\n");
 printf("Please input the second array:");
 for (i = 0; i < 5; i++)
  printf("%d ", b[i]);
 printf("\n");
 system("pause");
 return 0;
}
void swap(int* x, int* y) {
 int t;
 t = *x; *x = *y; *y = t; //进行每个元素的交换
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

方法三:引入第三个数组进行元素的交换,显然比较麻烦,这里不做介绍

方法四:引入第三变量,再利用strcpy函数进行交换各数组元素
              优势:对于两个数组的大小可不相等,均可进行交换
源代码:

#include<stdio.h> 
#include<stdlib.h> 
int main(){ 
 char str1[20];   
 char str2[20];   
 char str3[20];   
 puts("请输入str1的字符:");   
 gets(str1);   
 puts("请输入str2的字符:");   
 gets(str2);   
 strcpy(str3,str1);     //利用strcpy函数进行数组内容的交换,数组内容可不一样大
 strcpy(str1,str2);   
 strcpy(str2,str3);  
 puts("互换后的str1数组为:\n");  
 puts(str1);  
 printf("\n");  
 puts("互换后的str2数组为:\n");  
 puts(str2);  
 printf("\n");  
 system("pause");
 return 0; 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

总结:相比较方法二,方法一更为简单明了,易于理解。方法二涉及指针,但也是在利用第三个变量的基础上来完成的,因此建议使用方法一。如果两个数组的大小不相等或有字符,则建议使用方法三。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/思考机器/article/detail/63059
推荐阅读
相关标签
  

闽ICP备14008679号