使用指针对三个数排序
#include <stdio.h>int main()
{
int a, b, c, t;
int *pa, *pb, *pc;
printf("请输入三个数:");
scanf("%d%d%d", &a, &b, &c);
pa = &a;
pb = &b;
pc = &c;
if (a > b)
{
t = &pa;
*pa = *pb;
*pb = t;
}
if (a > c)
{
t = *pa;
*pa = *pc;
*pc = t;
}
if (b > c)
{
t = *pb;
*pb = *pc;
*pc = t;
}
printf("%d <= %d <= %d\n", *pa, *pb, *pc);
return 0;
}
请问这个警告和结果中的“6487544”是怎么回事? 不细心造成的,那个“6487544”应该是地址,&是取地址,pa是指针,&pa取指针pa的地址
// 应该是啊!仅供参考,我不是大佬,我是菜鸟
#include <stdio.h>
int main()
{
int a, b, c, t;
int *pa, *pb, *pc;
printf("请输入三个数:");
scanf("%d%d%d", &a, &b, &c);
pa = &a;
pb = &b;
pc = &c;
if (a > b)
{
t = *pa; // 这里错误了
*pa = *pb;
*pb = t;
}
if (a > c)
{
t = *pa;
*pa = *pc;
*pc = t;
}
if (b > c)
{
t = *pb;
*pb = *pc;
*pc = t;
}
printf("%d <= %d <= %d\n", *pa, *pb, *pc);
return 0;
}
{:10_277:} 本帖最后由 jackz007 于 2021-9-22 20:59 编辑
#include <stdio.h>
void swap(int ** pa , int ** pb)
{
int * p ;
p = * pa ;
* pa = * pb ;
* pb = p ;
}
int main(void)
{
int a , b , c , * p1 = & a , * p2 = & b , * p3 = & c ;
printf("请输入三个数:") ;
scanf("%d%d%d" , p1 , p2 , p3) ;
if(* p1 > * p2) swap(& p1 , & p2) ;
if(* p1 > * p3) swap(& p1 , & p3) ;
if(* p3 < * p2) swap(& p3 , & p2) ;
if(* p3 < * p1) swap(& p3 , & p1) ;
printf("%d <= %d <= %d\n" , * p1 , * p2 , * p3) ;
}
编译、运行实况:
D:\00.Excise\C>g++ -o x x.c
D:\00.Excise\C>x
请输入三个数:100 50 10
10 <= 50 <= 100
D:\00.Excise\C>x
请输入三个数:50 10 100
10 <= 50 <= 100
D:\00.Excise\C>x
请输入三个数:10 100 50
10 <= 50 <= 100
D:\00.Excise\C>x
请输入三个数:10 50 100
10 <= 50 <= 100
D:\00.Excise\C> #include <stdio.h>
int main()
{
int a, b, c, t;
int *pa, *pb, *pc;
printf("请输入三个数:");
scanf("%d%d%d", &a, &b, &c);//应该在%d和%d之间加一个空格
pa = &a;
pb = &b;
pc = &c;
if (a > b)
{
t = &pa;//这里应该是*pa
*pa = *pb;
*pb = t;
}
if (a > c)
{
t = *pa;
*pa = *pc;
*pc = t;
}
if (b > c)
{
t = *pb;
*pb = *pc;
*pc = t;
}
printf("%d <= %d <= %d\n", *pa, *pb, *pc);
return 0;
} 希望·别秃 发表于 2021-9-22 21:59
#include
int main()
感谢{:5_109:} jackz007 发表于 2021-9-22 20:54
编译、运行实况:
感谢指导{:5_110:} 开卷有益,多多益善····
页:
[1]