赞
踩
方法一:运用逻辑运算将数组中每个元素进行交换,在使用循环将整个数组元素交换
交换时创建第三变量来完成过程
源代码:
#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; }
方法二:利用指针函数进行交换各元素的值(需要对指针有一定的认识)
源代码:
#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; //进行每个元素的交换 }
方法三:引入第三个数组进行元素的交换,显然比较麻烦,这里不做介绍
方法四:引入第三变量,再利用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; }
总结:相比较方法二,方法一更为简单明了,易于理解。方法二涉及指针,但也是在利用第三个变量的基础上来完成的,因此建议使用方法一。如果两个数组的大小不相等或有字符,则建议使用方法三。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。