C++交換兩個數字的程式


有兩種方法可以建立一個交換兩個數字的程式。一種是使用臨時變數,另一種是不使用第三個變數。這些方法將詳細解釋如下:

使用臨時變數交換兩個數字的程式

使用臨時變數交換兩個數字的程式如下所示。

示例

 線上演示

#include <iostream >
using namespace std;
int main() {
   int a = 10, b = 5, temp;
   temp = a;
   a = b;
   b = temp;
   cout<<"Value of a is "<<a<<endl;
   cout<<"Value of b is "<<b;
   return 0;
}

輸出

Value of a is 5
Value of b is 10

在上面的程式中,有兩個變數a和b儲存兩個數字。首先,a的值儲存在temp中。然後,b的值儲存在a中。最後,temp的值儲存在b中。之後,a和b的值被交換。

temp = a;
a = b;
b = temp;

然後顯示a和b的值。

cout<<"Value of a is "<<a<<endl;
cout<<"Value of b is "<<b;

不使用第三個變數交換兩個數字的程式

不使用第三個變數交換兩個數字的程式如下所示:

示例

 線上演示

#include <iostream>
using namespace std;
int main() {
   int a = 10, b = 5;
   a = a+b;
   b = a-b;
   a = a-b;
   cout<<"Value of a is "<<a<<endl;
   cout<<"Value of b is "<<b;
   return 0;
}

輸出

Value of a is 5
Value of b is 10

在上面的程式中,首先將a和b的和儲存在a中。然後,將a和b的差儲存在b中。最後,將a和b的差儲存在b中。最終,a和b的值被交換。

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

然後顯示a和b的值。

cout<<"Value of a is "<<a<<endl;
cout<<"Value of b is "<<b;

更新於:2020年6月24日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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