Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
交换两个变量的值,由终端输入两个整数给变量x、y,然后交换x和y的值后,输出x和y。
Input
从键盘输入两个整数变量x和y;
Output
在交换x、y的值后将x和y输出!
Sample Input
4 6
Sample Output
6 4
Hint
Source
**方法一:**借助第三变量
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,y,z;
scanf("%d %d",&x,&y);
z=x; //将a的值暂时存在c中
x=y;
y=z;
printf ("%d %d\n",x,y);
return 0;
}
运行结果:
4 6
6 4
Process returned 0 (0x0) execution time : 03.125 s
Press any key to continue.
**方法二:**不借助第三变量
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,y;
scanf("%d %d",&x,&y);
x = x + y;
y = x - y; //y等于(x + y)- y;
x = x - y; //x等于(x+y)- [(x+y)-y];
printf ("%d %d\n",x,y);
return 0;
}
运行结果:
4 6
6 4
Process returned 0 (0x0) execution time : 04.687 s
Press any key to continue.
本文介绍了在C语言中交换两个变量值的两种常见方法:一种是使用第三个临时变量,另一种是通过数学运算实现,无需额外变量。文章提供了详细的代码示例及运行结果,适合初学者理解变量交换的基本原理。
816

被折叠的 条评论
为什么被折叠?



