C++ 实例 - 交换两个数

C++ 教程 · 2019-02-26 11:13:51

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

实例 - 使用临时变量

#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

点击查看所有 C++ 教程 文章: https://codercto.com/courses/l/18.html

查看所有标签

Cypherpunks

Cypherpunks

Julian Assange、Jacob Appelbaum、Andy Müller-Maguhn、Jérémie Zimmermann / OR Books / 2012-11 / GBP 8.99

Cypherpunks are activists who advocate the widespread use of strong cryptography (writing in code) as a route to progressive change. Julian Assange, the editor-in-chief of and visionary behind WikiLea......一起来看看 《Cypherpunks》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具