交换数组中的数值有关问题,请大家帮忙看看
交换数组中的数值问题,请大家帮忙看看!
#include <iostream>
using namespace std;
void exchange(int x,int y)
{
int t=x;
x=y;
y=t;
}
int main()
{
int a[2]={1,2};
cout < <a[0] < < " " < <a[1] < <endl;
exchange(a[0],a[1]);
cout < <a[0] < < " " < <a[1] < <endl;
return 0;
}
为什么这个exchange函数交换没有成功?
不用指针或引用能否解决这个问题。
------解决方案--------------------
用宏可以,不过那样就不是函数了
------解决方案--------------------
void exchange(int & x,int & y)
------解决方案--------------------
我就想用传值调用,看到书上好多这么写的。
--------------------------------------
传值是不可能交换的,一定要指针或者引用
要不就写宏了 - -!
#define exchange(x, y) {int t = x; x = y; y = t;}
------解决方案--------------------
引用 与地址传值。。
------解决方案--------------------
#define exchange(x, y) {int t = x; x = y; y = t;}
用宏可以实现,但缺点也是很明显的。
比如
exchange(x++, y++)
------解决方案--------------------
void exchange(int &x,int &y)
{
int t=x;
x=y;
y=t;
}
------解决方案--------------------
#include <iostream>
using namespace std;
void exchange(int *px,int *py)
{
int t=*px;
*px=*py;
*py=t;
}
int main()
{
int a[2]={1,2};
cout < <a[0] < < " " < <a[1] < <endl;
exchange(&a[0],&a[1]);
cout < <a[0] < < " " < <a[1] < <endl;
return 0;
}
------解决方案--------------------
宏应该这样写:
#define exchange((x), (y)) {int t = x; x = y; y = t;}
------解决方案--------------------
哦,上面写错了,应该这样:
#define exchange(x,y) {int t = (x); (x) = (y); (y) = t;}
#include <iostream>
using namespace std;
void exchange(int x,int y)
{
int t=x;
x=y;
y=t;
}
int main()
{
int a[2]={1,2};
cout < <a[0] < < " " < <a[1] < <endl;
exchange(a[0],a[1]);
cout < <a[0] < < " " < <a[1] < <endl;
return 0;
}
为什么这个exchange函数交换没有成功?
不用指针或引用能否解决这个问题。
------解决方案--------------------
用宏可以,不过那样就不是函数了
------解决方案--------------------
void exchange(int & x,int & y)
------解决方案--------------------
我就想用传值调用,看到书上好多这么写的。
--------------------------------------
传值是不可能交换的,一定要指针或者引用
要不就写宏了 - -!
#define exchange(x, y) {int t = x; x = y; y = t;}
------解决方案--------------------
引用 与地址传值。。
------解决方案--------------------
#define exchange(x, y) {int t = x; x = y; y = t;}
用宏可以实现,但缺点也是很明显的。
比如
exchange(x++, y++)
------解决方案--------------------
void exchange(int &x,int &y)
{
int t=x;
x=y;
y=t;
}
------解决方案--------------------
#include <iostream>
using namespace std;
void exchange(int *px,int *py)
{
int t=*px;
*px=*py;
*py=t;
}
int main()
{
int a[2]={1,2};
cout < <a[0] < < " " < <a[1] < <endl;
exchange(&a[0],&a[1]);
cout < <a[0] < < " " < <a[1] < <endl;
return 0;
}
------解决方案--------------------
宏应该这样写:
#define exchange((x), (y)) {int t = x; x = y; y = t;}
------解决方案--------------------
哦,上面写错了,应该这样:
#define exchange(x,y) {int t = (x); (x) = (y); (y) = t;}