不使用第三個變數在 C/C++ 中交換兩個變數值


以下是交換兩個變數的一個示例。

示例

 即時演示

#include <stdio.h>
int main() {
   int a,b;
   printf("Enter the value of a : ");
   scanf("%d", &a);
   printf("\nEnter the value of b : ");
   scanf("%d", &b);
   a += b -= a = b - a;
   printf("\nAfter Swapping : %d\t%d", a, b);
   return 0;
}

輸出

Enter the value of a : 23
Enter the value of b : 43
After Swapping : 4323

在以上的程式中,兩個變數 a 和 b 在執行時是動態宣告和初始化的。

int a,b;
printf("Enter the value of a : ");
scanf("%d", &a);
printf("\nEnter the value of b : ");
scanf("%d", &b);

無需使用任何第三方變數,就可以交換數字。

a += b -= a = b - a;

更新於: 2020 年 6 月 26 日

475 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.