TA的每日心情 | 汗 2024-10-15 10:05 |
---|
签到天数: 372 天 [LV.9]以坛为家II
|
如果有变量a=10, b=11,将a、b两变量的值进行交换,如何操作?
1、使用第三个变量temp- #include <stdio.h>
- int main() {
-
- int a = 10;
- int b = 11;
- printf("Before switch:\n a=%d, b=%d\n", a, b);
- int temp;
- temp = a;
- a = b;
- b = temp;
- printf("After switch:\n a=%d, b=%d\n",a ,b);
-
- }
复制代码 2、通过运算相互交换- #include <stdio.h>
- int main() {
-
- int a = 10;
- int b = 11;
-
- printf("Before switch:\n a=%d, b=%d\n", a, b);
-
- a = a + b;
- b = a - b;
- a = a - b;
-
- printf("After switch:\n a=%d, b=%d\n",a ,b);
-
- }
复制代码 PS:第二种方法需要一定的空间想像能力!! |
|