c - 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;
}
解决方案
(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)
推荐阅读
- javascript - Django 中的 Javascript console.log 命令不起作用?
- python - 如何将值数组和掩码组合成矩阵?
- database - WIX 数据库的 POST http 请求给出错误
- ios - 如何从 iOS 应用邀请 Facebook 好友?
- python - 训练模型字符识别的准确性没有提高
- python - 如何用多列的值计数按组汇总 pandas DataFrame?
- c# - 如何为静态库创建 C++ 或 C++/CLI 包装器以在 C# 中使用
- c++ - cin 在 C++ 中不接受带有空格的输入吗?
- asp.net - Saml2RequestException:断言已过期。断言有效的 NotOnOrAfter
- android - RecyclerView 和 cardView onclick