简体   繁体   English

如何使用多个嵌套三元运算符返回值

[英]How to use multiple nested ternary operators to return a value

I am looking at using a multiple nested ternary operators. 我正在寻找使用多个嵌套的三元运算符。 I have 3 values I want to compare. 我有3个值要比较。 All 3 are integers. 所有3个都是整数。 For example: 例如:

val1
val2
threshold

From all this I want a result of 1 or 0 . 从这一切我想要10的结果。

So, if I was to do this using if-else statements, my logic will look like this: 因此,如果要使用if-else语句执行此操作,则我的逻辑将如下所示:

if (val1 - val2 > threshold)
{
    result = 1;
}
else if (val2 - val1 > threshold)
{
    result = 1;
}

So far I have this: 到目前为止,我有这个:

int d = (alpha < 0 ? -alpha : alpha) > threshold ? (alpha < 0 ? -alpha : alpha) : 1;

which, although it compiles, does not give me the same result... 尽管可以编译,但不会给我相同的结果...

result = (val1 - val2 > thresold) ? 1 : (val2-val1 > thresold) ? 1 : 0;

Or 要么

result = (val1 - val2 > thresold) || (val2-val1 > thresold) ? 1 : 0;

Or 要么

result = Math.Abs(val1 - val2) > thresold ? 1 : 0;
result = val1 - val2 > threshold ? 1 : val2 - val1 > threshold ? 1 : 0

Why not this: 为什么不这样:

int d = (val1 - val2 > threshold) || (val2 - val1 > threshold) ? 1 : 0;

However, consider carefully if this is more readable than the if statements. 但是,请仔细考虑它是否比if语句更具可读性。 Indescriminate use of the ?: operator can make it more difficult to read and comprehend code. 随意使用?:运算符会使阅读和理解代码更加困难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM