网站首页 网站地图
网站首页 > 娱乐人生 > c语言里怎么编程求三个数的最大值和最小值

c语言里怎么编程求三个数的最大值和最小值

时间:2026-03-20 23:20:30

在C语言中,求三个数的最大值和最小值可以通过多种方法实现。以下是几种常见的方法:

方法一:使用比较函数

```c

include

// 返回最大值

int compare1(int a, int b) {

return a > b ? a : b;

}

// 返回最小值

int compare2(int a, int b) {

return a < b ? a : b;

}

int main() {

int a, b, c;

int max = 0; // 3个数中的最大值

int min = 0; // 3个数中的最小值

printf("请输入三个整数:");

scanf("%d%d%d", &a, &b, &c);

max = compare1(compare1(a, b), c);

min = compare2(compare2(a, b), c);

printf("\n其中最大值是 max=%d, 最小值 min=%d\n", max, min);

return 0;

}

```

方法二:使用嵌套条件语句

```c

include

int main() {

int a, b, c, max, min;

printf("请输入三个数:\n");

scanf("%d%d%d", &a, &b, &c);

// 求最大值

if (a > b) {

if (a > c) {

max = a;

} else {

max = c;

}

} else {

if (b > c) {

max = b;

} else {

max = c;

}

}

// 求最小值

if (a < b) {

if (a < c) {

min = a;

} else {

min = c;

}

} else {

if (b < c) {

min = b;

} else {

min = c;

}

}

printf("最大值: %d\n最小值: %d\n", max, min);

return 0;

}

```

方法三:使用条件运算符

```c

include

int main() {

int a, b, c;

int max;

printf("请输入三个整数:");

scanf("%d%d%d", &a, &b, &c);

max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);

printf("三个数中的最大值是:%d\n", max);

return 0;

}

```

方法四:使用`fmax`函数(C99标准)

```c

include

include

int main() {

double a, b, c;

double max;

printf("请输入三个数:\n");

scanf("%lf%lf%lf", &a, &b, &c);

max = fmax(fmax(a, b), c);

printf("最大值是: %lf\n", max);

return 0;

}

```

总结

以上方法都可以用来求三个数的最大值和最小值。方法一和方法二使用了传统的条件语句,方法三使用了条件运算符,方法四则利用了C99标准中的`fmax`函数。根据具体需求和编译器支持情况,可以选择合适的方法。