一道C++编程问题,定义变量交换函数swap(),将两个整型变量交换数据后输出。

来源:百度知道 编辑:UC知道 时间:2024/06/04 12:18:10

#include<iostream.h>
void swap(int &a,int &b)
{
int c;
c=a;
a=b;
b=c;
}
void main(){
int x,y;
cout<<"请输入两个整数:"
cin>>x>>y;
swap(x,y);
cout<<"输出交换后的结果:";
cout<<x<<" "<<y;
cout<<endl;
}

#include<iostream>

using namespace std;

void swap(int *a,int *b)
{
int *temp;
temp=a;
a=b;
b=temp;
}
int main()
{int x,y;
cout<<"输入二个数";
cin>>x>>y;
swap(x,y);

cout<<"交换输出是:";
cout<<x<<" " <<y<<endl;
return 0;
}

同样可以实现交换目的的函数!

void swap(int& a, int& b){
a=a+b;
b=a-b;
a=a-b;
}