一题C语言题目

来源:百度知道 编辑:UC知道 时间:2024/09/21 19:55:15
#include <stdio.h>
void exchange(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
void main()
{
int a=1;
int b=5;
exchange(a,b);
printf("now the value of a is %d\n the value of b is %d\n",a,b);
}
执行后没错误,只是a、b的值没交换。。怎么回事?
该如何修改???

要分清传值传递和传值传递.谭浩强的c书中解释的很详细.a,b的值在exchange()这个函数中是交换了的,但是,这个交换的值是不能传到主函数里面去的.应该将这个函数体的形参定义为引用或者指针.将函数体定义为void exchange(int &x,int &y)其余的不变,就可以达到你的效果了.

void exchange(int *x, int *y)//使用指针 实现
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
void main()
{
int a=1;
int b=5;
exchange(&a,&b);//传入其地址
printf("now the value of a is %d\n the value of b is %d\n",a,b);
}