0

对于我的 C++ 编程课程中的作业,我得到了以下代码。作业只是说“这个程序应该给出以下数字的 AND” 想知道是否可以澄清含义。我有一个想法,但我认为我仍然需要一些建议。提供的代码是故意混乱的,我必须清理一下。这里是清理:

// 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; 
}
4

3 回答 3

3

每个数字都有一个二进制表示。他们要求逻辑和位。查找&运营商。

于 2013-11-09T22:53:19.807 回答
1

'&' 是按位与,这意味着它采用两个数字的二进制表示,并将第一个数字中的每个位与第二个数字中相同位置的位进行比较。如果两者都为 1,则输出编号中相同位置的结果位为 1,否则该位为零。 if (i&k)将具有相同的结果(假设输入始终为 0 或 1),但无论如何,您的 if 语句会比较第一位是 0 还是 1,如果两者都是 1,则返回一个。

于 2013-11-09T22:55:28.853 回答
0
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.
于 2013-11-09T22:59:09.720 回答