xor 与 3 个值 [英] xor with 3 values

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

问题描述

我需要在 3 个值之间做一个异或条件,即我需要三个值之一为真,但不超过一个且不为无.

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,但事实并非如此.(真^真^真)

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.

为确保您得到您想要的结果(只有一个值为真),请执行以下操作:

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.

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

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