将三个数按从小到大输出

来源:互联网 发布:云计算培训课程 编辑:程序博客网 时间:2024/05/25 05:37

1、这道题,我采用了(1)创建临时变量的方法来解决;(2)用swap()函数来解决(注意:在引用数学函数的时候,必须引用“#include<stdio.h>”)。(1)这个方法在前面的《给定两个整形变量的值,将两个值的内容进行交换》中介绍过,有兴趣的朋友可以看看,加深一下对着种方法的理解。

(1)创建临时变量

#include<stdio.h>
#include<windows.h>
int main()
{
int a = 0;
int b = 0;
int c = 0;
int tmp;//创建临时变量
scanf("%d%d%d",&a,&b,&c);

        //在以下三个if语句中,都通过临时变量将两个变量的值的内容进行了交换,从而达到排序的目的

if(a > b)
{
tmp = a;
a = b;
b = tmp;
}
if(a > c)
{
tmp = a;
a = c;
c = tmp;
}
if(b > c)
{
tmp = b;
b = c;
c = tmp;
}
printf("%d %d %d",a,b,c);
system("pause");
return 0;
}

(2)用swap()函数

#include<stdio.h>
#include<math.h>
#include<windows.h>
int main()
{
int a = 0;
int b = 0;
int c = 0;
scanf("%d%d%d", &a, &b, &c);
if(a < b)
{
Swap(&a, &b);
}
if(a < c)
{
Swap(&a, &c);
}
if(b < c)
{
Swap(&b, &c);
}


printf("%d %d %d\n", a, b, c);
system("pause");
return 0;
}

原创粉丝点击