问题描述
我必须找到用户提供的最多三个数字,但有一些限制.不允许使用任何条件语句.我尝试使用如下三元运算符.
I have to find maximum of three number provided by user but with some restrictions. Its not allowed to use any conditional statement. I tried using ternary operator like below.
max=(a>b?a:b)>c?(a>b?a:b):c
但它再次限制使用三元运算符.现在我不知道该怎么做?
But again its restricted to use ternary operator.Now I am not getting any idea how to do this?
推荐答案
利用布尔表达式中的短路:
Taking advantage of short-circuiting in boolean expressions:
int max(int a, int b, int c)
{
int m = a;
(m < b) && (m = b); //these are not conditional statements.
(m < c) && (m = c); //these are just boolean expressions.
return m;
}
说明:
在 x && 等布尔
, y 被评估当且仅当 AND
操作中yx
为真.如果 x
为假,则不计算 y
,因为整个表达式将为假,甚至可以在不计算 y
的情况下推导出.当布尔表达式的值可以在不计算其中所有操作数的情况下推导出来时,这称为短路.
In boolean AND
operation such as x && y
, y is evaluated if and only if x
is true. If x
is false, then y
is not evaluated, because the whole expression would be false which can be deduced without even evaluating y
. This is called short-circuiting when the value of a boolean expression can be deduced without evaluating all operands in it.
将这个原则应用到上面的代码中.最初 m
是 a
.现在如果 (m < b)
为真,那么这意味着 b
大于 m
(实际上是 a
),所以第二个子表达式 (m = b)
被计算并且 m
被设置为 b
.但是,如果 (m < b)
为假,则不会计算第二个子表达式并且 m
将保持为 a
(大于 ).以类似的方式,计算第二个表达式(在下一行).
Apply this principle to the above code. Initially m
is a
. Now if (m < b)
is true, then that means, b
is greater than m
(which is actually a
), so the second subexpression (m = b)
is evaluated and m
is set to b
. If however (m < b)
is false, then second subexpression will not be evaluated and m
will remain a
(which is greater than b
). In a similar way, second expression is evaluated (on the next line).
简而言之,您可以阅读表达式 (m < x) &&(m = x)
如下:将 m
设置为 x
当且仅当 m
是小于 x
即 (m < x)
为真.希望这可以帮助您理解代码.
In short, you can read the expression (m < x) && (m = x)
as follows : set m
to x
if and only if m
is less than x
i.e (m < x)
is true. Hope this helps you understanding the code.
测试代码:
int main() {
printf("%d
", max(1,2,3));
printf("%d
", max(2,3,1));
printf("%d
", max(3,1,2));
return 0;
}
输出:
3
3
3
注意 max
的实现会给出警告,因为没有使用评估表达式:
Note the implementation of max
gives warnings because evaluated expressions are not used:
prog.c:6:警告:未使用计算的值
prog.c:7:警告:未使用计算的值
为避免这些(无害的)警告,您可以将 max
实现为:
To avoid these (harmless) warnings, you can implement max
as:
int max(int a, int b, int c)
{
int m = a;
(void)((m < b) && (m = b)); //these are not conditional statements.
(void)((m < c) && (m = c)); //these are just boolean expressions.
return m;
}
诀窍在于,现在我们将布尔表达式转换为void
,这会导致警告被抑制:
The trick is that now we're casting the boolean expressions to void
, which causes suppression of the warnings:
这篇关于在不使用条件语句和三元运算符的情况下,在 C 中查找最多三个数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!