简体   繁体   English

在公民投票中使用C位运算符 - 家庭作业

[英]Using C Bitwise Operators in a Referendum - Homework

I'm doing a C homework project and I'm incredibly lost. 我正在做一个C家庭作业项目而且我非常迷失。 Essentially, I have to make function called majority that takes in 3 short integers, and spits out another number based on the inputs. 本质上,我必须使函数称为多数 ,它接受3个短整数,并根据输入吐出另一个数字。 I'll give an example from the project: 我将从项目中给出一个例子:

Basically, I make the function majority(101010101010101, 101010101010101, 101010101010101) , and if there are 2 or more 1's in that bit, return 1, else return 0. 基本上,我使函数majority(101010101010101, 101010101010101, 101010101010101) ,如果该位有2个或更多1,则返回1,否则返回0。

Thus far, I have 到目前为止,我有

short majority(short a, short b, short c)
{
    return (a | b | c);
}

Now, I know that this isn't right at all , so I'm asking here: How would I go about doing this? 现在,我知道这是不对的根本 ,所以我在这里问:我怎么会去这样做呢? Thank you for the help, and I apologize if this is kinda hard to follow. 感谢您的帮助,如果有点难以理解,我深表歉意。 I can edit as necessary. 我可以根据需要进行编辑。

There's more than one way of doing this, but one possibility is: 这样做的方法不止一种,但有一种可能性是:

short majority(short a, short b, short c)
{
    return (a & b) | (b & c) | (c & a);
}

As this is homework I'll let you work for yourself out how/why this works, and see if you can come up with an alternate, perhaps even better solution... 由于这是家庭作业,我会让你为自己工作如何/为什么这样做,看看你是否可以提出一个替代,甚至更好的解决方案......

If I understand you correctly, you want a bit set in a result integer if and only if the corresponding bit is set in two or three input integers. 如果我理解正确,那么当且仅当相应的位设置为两个或三个输入整数时,您需要在结果整数中设置一个位。

... so that's if the bit is set in the first number and the corresponding bit is set in either of the last two numbers or the corresponding bit is set in both of the last two numbers, so in a bitwise expression: ...这样,如果该位在第一个数字中设置,并且相应的位在最后两个数字中的任何一个中设置,或者在最后两个数字中都设置了相应的位,那么在按位表达式中:

result = (a & (b | c)) | (b & c);

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

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