指针交换变量的值
#include <stdio.h>int main(void)
{
long a, b, c;
long *d, *e, *f, *g;
printf("请输入三个数:");
scanf("%d%d%d",&a, &b, &c);
d = &a;
e = &b;
f = &c;
if(a > b)
{
d = &b;
e = &a;
}
if(a > c)
{
d = &c;
f = &a;
}
if(b > c)
{
e = &c;
f = &b;
}
printf("%d <= %d <= %d\n",*d,*e,*f);
return 0;
}
我这里直接改变指针指向的值为什莫不行,不理解
那应该怎末该呢 本帖最后由 jhq999 于 2021-10-25 22:21 编辑
如果a>b
d=&b
下面a>c 这时d!=&a而是&b,
如果b<c
运行后d=&c,e=&a,f=&a 本帖最后由 jackz007 于 2021-10-25 22:50 编辑
用三目运算符可以大幅度简化代码:
#include <stdio.h>
int main(void)
{
int a , b , c , * d , * e , * f ;
scanf("%d%d%d" , & a , & b , & c) ;
d = (a < b && a < c) ? & a : (b < a && b < c) ? & b : & c ;
e = ((a > b && a < c) || (a < b && a > c)) ? & a : ((b > a && b < c) || (b < a && b > c)) ? & b : & c ;
f = (a > b && a > c) ? & a : (b > a && b > c) ? & b : & c ;
printf("%d <= %d <= %d\n" , * d , * e , * f) ;
}
编译、运行实况:
D:\00.Excise\C>g++ -o x x.c
D:\00.Excise\C>x
100 200 300
100 <= 200 <= 300
D:\00.Excise\C>x
200 100 300
100 <= 200 <= 300
D:\00.Excise\C>x
300 100 200
100 <= 200 <= 300
D:\00.Excise\C>x
300 200 100
100 <= 200 <= 300
D:\00.Excise\C>
页:
[1]