## C语言关于交换数值的一些内容

1.交换两个数的值

``````#include <stdio.h>
#include <stdlib.h>
int main(){
int a = 2;
int b = 3;
printf("交换前的值a=%d,b=%d\n", a, b);
int temp;//利用第三个变量进行交换
temp = a;
a = b;
b = temp;
printf("交换后的值a=%d,b=%d\n", a, b);
system("pause");
return 0;
}
``````

2.不用第三变量换两个数的值

``````#include <stdio.h>
#include <stdlib.h>
int main(){
int a = 2;
int b = 3;//不加第三变量
printf("交换前的值a=%d,b=%d\n", a, b);
a = a + b;//利用加减法的特性
b = a - b;
a = a - b;
printf("交换后的值a=%d,b=%d\n", a, b);
system("pause");
return 0;
}
``````

3.求十个数中的最大值

``````#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main(){
int count = 1,b;
printf("请输入十个数:\n");
for (count = 1; count <= 10; count++){
int a = 0;
scanf("%d", &a);
if (count==1||b <= a){  //利用或将第一次a的值赋给b
b = a;
}
}
printf("%d\n", b);
system("pause");
return 0;
}
``````

4.将三个数从小到大输出

``````#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define Size  3
int main(){
printf("Enter three numbers:\n");
int a[Size];
for (int i = 0; i <= Size-1; i++)
scanf("%d", &a[i]);
for (int j = 0; j < Size - 1;j++)
for (int i = 0; i <Size-1-j ; i++){//a[Size-1-j]已经被确定所以不需要在确认
if (a[i] < a[i + 1]){
a[i] = a[i] + a[i+1];//利用加减法的特性进行交换
a[i + 1] = a[i] - a[i + 1];
a[i] = a[i] - a[i + 1];
}
}
for (int i = 0; i <= Size - 1; i++)
printf("%d ", a[i]);
system("pause");
return 0;
}
``````

5.求两个数的最大公约数

``````#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main(){
printf("Enter two numbers:");
int a, b;
scanf("%d %d", &a, &b);
if (a < b){
a = a + b;
b = a - b;//运用交换排大小
a = a - b;
}
int c = a;
while (a%b != 0){
c = a%b;
a = b;           //运用交换两个数以及辗转相除法
b = c;
}
printf("%d \n", b);
system("pause");
return 0;
}
``````