早教吧作业答案频道 -->其他-->
#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的值没有交换?
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);
}
#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...的网友还看了以下:
#includevoidswap(intx,inty){inttemp;temp=x;x=y;y= 2020-07-23 …
C++中数据互换voidswap(intx,inty){inttemp=x;x=y;y=temp;} 2020-12-23 …