C++ 实例 – 交换两个数

星河私藏家

C++ 实例 - 交换两个数

以下我们使用两种方法来交换两个变量:使用临时变量与不使用临时变量。

实例 - 使用临时变量

#include <iostream>
using namespace std;
 
int main()
{
    int a = 5, b = 10, temp;
 
    cout << "交换之前:" << endl;
    cout << "a = " << a << ", b = " << b << endl;
 
    temp = a;
    a = b;
    b = temp;
 
    cout << "\n交换之后:" << endl;
    cout << "a = " << a << ", b = " << b << endl;
 
    return 0;
}

以上程序执行输出结果为:

交换之前:
a = 5, b = 10

交换之后:
a = 10, b = 5

实例 - 不使用临时变量

#include <iostream>
#include <iostream>
using namespace std;
 
int main()
{
    
    int a = 5, b = 10;
 
    cout << "交换之前:" << endl;
    cout << "a = " << a << ", b = " << b << endl;
 
    a = a + b;
    b = a - b;
    a = a - b;
 
    cout << "\n交换之后:" << endl;
    cout << "a = " << a << ", b = " << b << endl;
 
    return 0;
}

以上程序执行输出结果为:

交换之前:
a = 5, b = 10

交换之后:
a = 10, b = 5
版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com

目录[+]

取消
微信二维码
微信二维码
支付宝二维码