在 C 程式語言中使用位運算子交換數字


問題

如何在 C 程式語言中使用位運算子交換數字?

解決方案

編譯器交換給定的數字,首先將給定的十進位制數轉換為二進位制等價數,然後執行按位異或運算以從一個記憶體位置交換到另一個記憶體位置。

演算法

START
Step 1: declare two variables a and b
Step 1: Enter two numbers from console
Step 2: swap two numbers by using BITWISE operator
        a=a^b
        b=a^b
        a=a^b
Step 3: Print a and b values
STOP

程式

 線上演示

#include<stdio.h>
int main(){
   int a,b;
   printf("enter the values for a and b:");
   scanf("%d%d",&a,&b);
   printf("value of a=%d and b=%d before swap
",a,b);    a= a^b;    b= a^b;    a= a^b;    printf("value of a=%d and b=%d after swap",a,b);    return 0; }

輸出

enter the values for a and b:24 56
value of a=24 and b=56 before swap
value of a=56 and b=24 after swap
Explanation:
a=24 binary equivalent of 24 =011000
b=56 binary equivalent of 56= 111000
a= a^b = 100000
b=a^b=100000 ^ 111000 =011000
a=a^b=100000 ^ 011000 = 111000
Now a=111000 decimal equivalent =56
b= 011000 decimal equivalent = 24

更新於: 2021-03-05

18K+ 瀏覽量

開啟你的 職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.