c语言中,如果要从小到大的顺序依次输出a,b,c。先比较a和b的值,如果a大于b,,则利用t把a和b进行交换;

如果要从大到小,是否要中间变量t来交换

还是给你代码吧,估计你没搞明白怎么使用临时变量。
/***
* Name: three numbers sort sample
* Autor:BIOHAZARDX(AirStorm)
* Data: 2012/04/05
* Version: 0.1
* License: Free
***/

#include <stdio.h>

// 升序排列实现函数
int uppersort(int *a, int *b, int *c)
{
int temp = 0; // 临时变量,需要
int result = 0;
// a 大于 b 的情况
if (*a > *b)
{
temp = *a;
*a = *b;
*b = temp;
result = 1;
}
// a 大于 c 的情况
if (*a > *c)
{
temp = *a;
*a = *c;
*c = temp;
result = 1;
}
// b 大于 c 的情况
if (*b > *c)
{
temp = *b;
*b = *c;
*c = temp;
result = 1;
}

return result;
}

// 降序排列实现函数
int lowersort(int *a, int *b, int *c)
{
int temp = 0; // 临时变量,需要
int result = 0;
// a 小于 b 的情况
if (*a < *b)
{
temp = *a;
*a = *b;
*b = temp;
result = 1;
}
// a 小于 c 的情况
if (*a < *c)
{
temp = *a;
*a = *c;
*c = temp;
result = 1;
}
// b 小于 c 的情况
if (*b < *c)
{
temp = *b;
*b = *c;
*c = temp;
result = 1;
}

return result;
}

// 主控制台
int main(void)
{
int a = 1, b = 2, c = 3; // 默认输入规则为升序,可以任意定制
int result;
// 按照输入的规则,先进行降序排列
if (1 == (result = lowersort(&a, &b, &c)))
{
printf("lower sort ok\n");
printf("a = %d, b = %d, c = %d\n", a, b, c);
}
else
{// 排列失败情况考虑
printf("lower sort ng\n");
printf("a = %d, b = %d, c = %d\n", a, b, c);
}
// 升序排列
if (1 == (result = uppersort(&a, &b, &c)))
{
printf("upper sort ok\n");
printf("a = %d, b = %d, c = %d\n", a, b, c);
}
else
{// 排列失败情况考虑
printf("upper sort ng\n");
printf("a = %d, b = %d, c = %d\n", a, b, c);
}
}

以上代码使用gcc4.2编译通过。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-04-04
都需要中间变量的。
只是中间变量看个人的定义,你可以定义自己的中间变量,随便叫什么名字。
第2个回答  2012-04-04
都是通过赋值来进行交换的,所以必须要有中间变量的
第3个回答  2012-04-04
需要,要不怎么交换呢
第4个回答  2012-04-04
需要
相似回答