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;
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP