用c語言編寫兩個數的交換,三種方法
阿新 • • 發佈:2018-12-30
下面是從函式角度,還有簡單的交換 法去實現兩個數的交換。其中函式用到指標,通過前兩種方法可以深刻的體會到指標變得的含義。
#include <stdio.h>
void swap(int *a,int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int x=2, y=5;
int *m,*p;
m=&x;
p=&y;
swap(m,p);
printf("%d,%d",x,y);
}
#include <stdio.h>
void main()
{
int a,b,temp;
a=2;b=5;
temp=a;
a=b;
b=temp;
printf("%d,%d",a,b);
}
#include <stdio.h>
void swap(int *a,int *b)
{
int *temp;
temp=a;
a=b;
b=temp;
printf("%d,%d",*a,*b);
}
void main()
{
int x=2, y=5;
int *m,*p;
m=&x;
p=&y;
swap(m,p);
}