请懂C语言的朋友帮看看?谢谢!

来源:百度知道 编辑:UC知道 时间:2024/05/30 10:32:20
为什么结果没有交换呢?
#include "stdio.h"
main()
{
int a,b;
scanf("%d,%d",&a,&b);
swap(a,b);
printf("%d,%d\n",a,b);

}
swap(int a,int b)
{int temp;
temp=b;b=a;a=temp;
}

你出现了以下问题

1.如果被调用函数在主调函数之后写,那么在主调函数里必须对被调函数进行声明
2.你写的函数没有返回值,而且就算有的话,函数也只能返回一个值,而你要返回两个值,当然不行了
3.如果你想用函数交换明显是要用到指针
4.如果你不想用指针,那么还不如不用函数
5.如果非要用函数,而不用指针那你要用全局变量
我给你写两种吧
**************************************************************
#include "stdio.h"
main()
{
int a,b,temp;
scanf("%d,%d",&a,&b);
temp=b;b=a;a=temp;
printf("%d,%d\n",a,b);
}

****************************************************************
#include "stdio.h"
void swap(int *p1, int *p2)
{
int temp;
temp=*p2;*p2=*p1;*p1=temp;
}
main()
{
int *p1,*p2;
int a,b;
p1=&a;
p2=&b;
scanf("%d,%d",p1,p2);
swap(p1,p2);
printf("%d,%d\n",a,b);

}

如果你觉得这个答案好,再给我点分吧,呵呵

1

swap(int& a,int& b)
{int temp;
temp=b;b=a;a=temp;
}

swap(a,b)