我要找到最大的用户,但有一些限制提供了三个号码。它不允许使用任何条件语句。我试着用三元操作符象下面这样。
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?
发生短路布尔EX pressions趁着:
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 当且仅当 X
是真实的。如果 X
为假,则是
不计算,因为整个EX pression是false,这可以推断甚至没有评估是
。这就是所谓的短路时,可以不评估所有的操作数在其推断的布尔EX pression的价值。
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.
将这一原则上述code。最初 M
是 A
。现在,如果(M&LT; B)
是真实的,那么这意味着, B
大于 M
(这实际上是 A
),所以第二个SUBEX pression (M = B)
评估和 M
设置为 B
。然而,如果(M&LT; B)
为假,则第二SUBEX pression将不进行评估, M
仍将 A
(大于 B
)。以类似的方式,第二前pression评估(下一行)。
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).
总之,你可以阅读EX pression (M&LT,X)及和放大器; (M = X)
如下:设置 M
到 X
如果和只有当 M
比 X小于即(M&LT; X)
是真实的。希望这有助于你了解code。
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.
测试code:
int main() {
printf("%d\n", max(1,2,3));
printf("%d\n", max(2,3,1));
printf("%d\n", max(3,1,2));
return 0;
}
输出:
3
3
3
在线演示: http://www.ideone.com/8045P
请注意实施最高
给出警告,因为评估EX pressions不使用:
Note the implementation of max
gives warnings because evaluated expressions are not used:
prog.c中:6:警告:价值计算,不使用 prog.c中:7:警告:未使用的价值计算
prog.c:6: warning: value computed is not used prog.c:7: warning: value computed is not used
要避免这些(无害的)警告,可以实现最高
为:
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;
}
诀窍是,现在我们casting布尔EX pressions到无效
,这将导致SUP $ P $的警告pssion 的:
The trick is that now we're casting the boolean expressions to void
, which causes suppression of the warnings: