首页 > 解决方案 > C语言中不使用if..else语句求最大值

问题描述

我试图在不使用 if...else 语句的情况下找到三个整数的最大值,当我进行一些搜索时,我遇到了这行代码。除了 abs 函数,我能理解的所有其他行.谁能解释代码中的abs函数是如何工作的?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x, y, z, result, max;

    printf("\nInput the first integer: "); 
    scanf("%d", &x);

    printf("\nInput the second integer: ");
    scanf("%d", &y);

    printf("\nInput the third integer: ");
    scanf("%d", &z);

    result=(x+y+abs(x-y))/2;
    max=(result+z+abs(result-z))/2;

    printf("\nMaximum value of three integers: %d\n", max);

    return 0;
}

标签: c

解决方案


(a+b+abs(a-b))/2

如果a>b那么这个表达式变成(a+b+(a-b))/2了 which is a
如果b>a那么这个表达式变成(a+b-(a-b))/2了 which is b

所以这个表达式只给你两个值的最大值。

为了获得三个值的最大值,您只需取前两个和第三个值的最大值。max(a,b,c) = max(max(a,b),c)


推荐阅读