C ++中带有布尔值的^(按位XOR)

问题描述 投票:0回答:2

我遇到了代码挑战。完成后,我查看了其他答案。我看到了一个我难以理解的答案。

#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"

bool willYou(bool young, bool beautiful, bool loved)
{
    return (young & beautiful) ^ loved;
}

TEST_CASE("willYou are computed", "[willYou]")
{
    REQUIRE(willYou(true, true, true) == false);
    REQUIRE(willYou(true, false, true) == true);
    REQUIRE(willYou(false, false, false) == false);
    REQUIRE(willYou(false, false, true) == true);
}

如果您需要为挑战提供的信息(在这里我认为它不是必需的)。

Once Mary heard a famous song, and a line from it stuck in her head. That line was "Will you still love me when I'm no longer young and beautiful?". Mary believes that a person is loved if and only if he/she is both young and beautiful, but this is quite a depressing thought, so she wants to put her belief to the test.

Knowing whether a person is young, beautiful and loved, find out if they contradict Mary's belief.

A person contradicts Mary's belief if one of the following statements is true:

they are young and beautiful but not loved;
they are loved but not young or not beautiful.
Example

For young = true, beautiful = true, and loved = true, the output should be
willYou(young, beautiful, loved) = false.

Young and beautiful people are loved according to Mary's belief.

For young = true, beautiful = false, and loved = true, the output should be
willYou(young, beautiful, loved) = true.

Mary doesn't believe that not beautiful people can be loved.

Input/Output

[execution time limit] 0.5 seconds (cpp)

[input] boolean young

[input] boolean beautiful

[input] boolean loved

[output] boolean

true if the person contradicts Mary's belief, false otherwise.

我无法理解的是在这里如何使用^运算符来获得所需的布尔结果?我使用Catch2创建了这些测试。从GeeksForGeeks开始,它只是声明...

C或C ++中的^(按位XOR)将两个数字用作操作数,并对两个数字的每一位进行XOR。如果两个位不同,则XOR的结果为1。

好吧,可以肯定的是,这里的true和false将是1和0。所以我认为在第一个测试用例中将返回1或true,但是它是false还是0?如果都为真,为什么会为假?我知道这个故事正试图在这里解释。但在故事中却说如果年轻美丽,那么您就被爱了。我不确定是否误解了该声明,还是只是一个不好的解释(我开始认为这是不好的)。无论如何,我需要帮助来尝试更多地了解此运算符,并基本上掌握所有这些含义。我只是在这里迷路了。

c++ boolean bitwise-operators bitwise-xor
2个回答
0
投票

我想我明白您要问的。我看到评论部分试图向您解释XOR的功能,这很有趣。无论如何,

问题表明,玛丽的信念是:“如果你年轻美丽,你就会被爱”。我们的目标是与Mary矛盾,并向她表明,有时候有人被爱过,但没有这两种或两种特质中的一种,如果有人做到了但又不被爱,则OR

简而言之

,我们的目的是与她的信念相矛盾。willYou()函数的输出是检查

if

我们是否可以与Mary矛盾。也许您可以通过处理各种情况并为每种情况提供输出来解决此问题。您的问题中提到的解决方案是通用解决方案。如果表达式中的奇数个数为1,则XOR运算符将返回1。例如:

    如果young = 1和beautiful = 1,则它们的AND为1,与被爱者的异或= 1为0(
  1. 即 false),因此不与> Mary矛盾。如果young = 0且beautiful = 1,则它们的AND为0,与被爱者的XOR为1(
  2. true),因此does与Mary矛盾。类似地,其他情况也可以形成这种形式。

    求解器必须使用XOR的“ passer / inverter”属性。只要输出对Mary有利,它就会使答案反过来使我们屈服false,这意味着我们不能与她矛盾。我认为这只是一个人提出的创造性解决方案,可能不是一个令人难以置信的问题(在这里根本不想屈服),这会使我们的生活更加轻松。

使用[in]等于运算符('=='作为xnor,'!='作为xor);

bool a,b;

...

bool c = a == b; // xnor

bool d = a!= b; // xor


0
投票
使用[in]等于运算符('=='作为xnor,'!='作为xor);

bool a,b;

© www.soinside.com 2019 - 2024. All rights reserved.