简体   繁体   English

该程序应提供以下数字的AND。 这是什么意思?

[英]This program should give the AND of the following numbers. What does this mean?

For an assignment in my C++ programming class, I was given the following code. 对于我的C ++编程类中的作业,给了我以下代码。 The assignment simply says "This program should give the AND of the following numbers" Was wondering if could get clarification on the meaning. 作业只说“该程序应给出以下数字的AND”,想知道是否可以弄清含义。 I have an idea but I think I still need a bit of advice. 我有一个主意,但我认为我仍然需要一些建议。 The code was provided jumbled on purpose which I had to clear up. 该代码是故意提供的,我必须清除。 Here is is cleaned up: 这里是清理:

// Question2
// This program should give the AND of the inputted numbers.

#include <iostream>

//**Needs namespace statement to directly access cin and cout without using std::
using namespace std;
//**Divided up statements that are running together for better readability
//**Used more spacing in between characters and lines to further increase readability

////void main()
//**Main function should include int as datatype; main is not typically defined as a void function
int main()
{
int i;
int k;

//**Changed spacing to properly enclose entire string
cout << "Enter 0 (false) or 1 (true) for the first value: " << endl;
cin >> i;

cout<< "Enter 0 (false) or 1 (true) for the second value: " << endl;
cin >> k;

//**Spaced out characters and separated couts by lines
//**to help with readability
cout << "AND" << endl;
cout << "k\t| 0\t| 1" << endl;
cout << "---\t| ---\t| ---" << endl;
cout << "0\t| 0\t| 0" << endl;
cout << "1\t| 0\t| 1" << endl;
    if(i==1&k==1)
        cout <<"Result is TRUE" << endl;
    else cout << "Result is FALSE" <<endl;
//**Main function typically includes return statement of 0 to end program execution
return 0; 
}

Every number has a binary representation. 每个数字都有一个二进制表示形式。 They're asking for the logical and of the bits. 他们要的是逻辑和细节。 Look up the & operator. 查找&运算符。

'&' is a bitwise and, which means it takes the binary representation of two numbers and compares each bit in the first number against the bit in the same position on the second. “&”按位表示,这意味着它采用两个数字的二进制表示并将第一个数字中的每个位与第二个相同位置中的位进行比较。 If both are 1, the resultant bit in the same position in the output number is 1, otherwise the bit is zero. 如果两者均为1,则输出编号中位于同一位置的结果位为1,否则该位为零。 if (i&k) would have the same result (assuming the input was always 0 or 1), but anyway your if statement compares whether the first bit is 0 or 1, and if both are 1 returns one. if (i&k)将具有相同的结果(假设输入始终为0或1),但是无论如何,if语句将比较第一位是0还是1,如果两者均为1,则返回1。

the AND gate(output) will be true only if both inputs are true(1)

true if i==1 && k==1
false if i==0 && k==0,i==1 && k==0,i==0 && k==1.

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

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