【分析】 交换两个变量的值方法很多,一般我们采用引入第三个变量的算法,二个变量交换,可以想像成一瓶酱油和一瓶醋进行交换,这时容易想到拿一个空瓶子过来:
① 将酱油倒到空瓶中;② 将醋倒到酱油瓶中;③ 将原空瓶中的酱油倒到醋瓶中。
程序如下:
#include<iostream> //使用cin,cout,须调用iostream库
using namespace std;
int main()
{ int a,b,c; //定义三个变量
cout<<"Input a,b="; //输入提示Input a,b=
cin>>a>>b; //输入A、B的值
c=a; a=b; b=c; //交换A、B的值
cout<<"a="<<a<<" b="<<b<<endl; //输出结果
}
#include<iostream> //使用cin,cout,须调用iostream库
using namespace std;
int main ()
{
int a,b,c; //定义3个变量
cout<<"Input a,b="; //输入提示inputa,b=
cin>>a>>b; //输入a,b的值
c=a;
a=b;
b=c; //交换a,b的值
cout<<"a="<<a<<" b="<<b<<endl; //输出结果
return 0;
}