具有3个值的xor [英] xor with 3 values

查看:60
本文介绍了具有3个值的xor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在3个值之间进行xor条件运算,即我需要三个值之一为true,但不超过一个且不为空.

I need to do an xor conditional between 3 values, ie i need one of the three values to be true but not more than one and not none.

我认为我可以为此使用xor ^运算符,但是它不能按预期工作.

I thought i could use the xor ^ operator for this but its not working as expected.

我希望这将返回false,但不会. (true ^ true ^ true)

I expected that this would return false but it doesnt. (true ^ true ^ true)

所有其他组合似乎都可以正常工作.

all other combinations seem to work as i expected.

在查看xor运算符的文档时,他们只谈论比较2个值,而我无法在线上为3个或更多值进行任何操作.

When looking at the docs for the xor operator they only talk about comparing 2 values and i cant find anything on doing this for 3 or more values online.

任何人都可以阐明或建议一种简单的方法吗?

Can anyone shed any light or suggest a simple way of doing this?

推荐答案

((true ^ true) ^ true)将返回true,这与您对true ^ true ^ true的期望不同.

((true ^ true) ^ true) will return true, which is not what you would expect from true ^ true ^ true.

要确保获得所需的结果(只有一个值为true),请执行以下操作:

To make sure that you get the outcome you want (only one value to be true) do the following:

if ((a && !b && !c) || (!a && b && !c) || (!a && !b && c))

或者,根据@jcomeau_ictx答案,您可以执行以下操作:

Alternatively, based on @jcomeau_ictx answer, you can do the following:

if( Convert.ToInt32(a) + Convert.ToInt32(b) + Convert.ToInt32(c) == 1 )

或者,您可以创建一个函数:

Or, you could create a function:

public bool TernaryXor(bool a, bool b, bool c)
{
    //return ((a && !b && !c) || (!a && b && !c) || (!a && !b && c));

    // taking into account Jim Mischel's comment, a faster solution would be:
    return (!a && (b ^ c)) || (a && !(b || c));
}

您可能想为函数TernaryXor命名,以便对函数的结果更清楚.

You might want to name the function TernaryXor so that it is more clear as to the outcome of the function.

这篇关于具有3个值的xor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆