使用Visual C++语言 编写一个函数完成两数交换,并用主函数调用它。(引用传递)

2025-02-02 14:52:03
推荐回答(3个)
回答1:

#include
void f(int *x, int *y){
int *t;
*t=*x;*x=*y;*y=*t;
}
main()
{

int a,b;
scanf("%d%d",&a,&b);
f(&a,&b);
printf("%d %d\n",a,b);

}

回答2:

首先Visual C++不是语言,是一个开发工具。
代码如下,使用模板,并且不使用中间变量交换

template
void exchange(T1& t1, T2& t2)
{
t1 = t1 + t2;
t2 = t1 - t2;
t1 = t1 - t2;
}
主函数中直接调用就行了,数据类型什么都可以,因为用了模板

回答3:

#include
using namespace std;

template
void swap(T& a, T& b)
{
T c;
c = a;a = b;b = c;
}

int main()
{
double a;
double b;
cin >> a;
cin >> b;
swap(a,b);
cout << "After swap():\n" << a << endl << b;
return 0;
}