早教吧 育儿知识 作业答案 考试题库 百科 知识分享

#includevoidswap(intx,inty){inttemp;temp=x;x=y;y=temp;}voidmain(){inta,b;scanf(“%d%d”,&a,&b);if(a>b)swap(a,b);printf(“%d\t%d”,a,b);}为什么a,b的值没有交换?

题目详情
#include
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
void main()
{
int a,b;
scanf(“%d%d”,&a,&b);
if(a>b)
swap(a,b);
printf(“%d\t %d”,a,b);
}
为什么a,b的值没有交换?
▼优质解答
答案和解析
函数都是值传递的,形参值的改变,并不能改变实参的值,要想改变,传地址.
#include
void swap(int *x,int *y) //这里是指针
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
void main()
{
int a,b;
scanf(“%d%d”,&a,&b);
if(a>b)
swap(&a,&b); //把ab的地址传过去.
printf(“%d\t %d”,a,b);
}
看了 #includevoidsw...的网友还看了以下: