APCS程式檢測 -實作題1061028 第1題 邏輯運算子

APCS程式檢測 -實作題1061028 第1題 邏輯運算子

如果不清楚二維陣列,可以先來這裡看看
https://husking-studio.com/cpp-2d-array/

就依照題目的說明準備 3 張表格去對照就可以了,測試資料那裡有說 0<= a,b < 10000,所以 a, b, result 就直接用 int 去處理,而不用 bool,這樣比較方便。

第一步:a 和 b 對應的 row 和 column

int GetARow(int a)
{
	if (a == 0)
		return 0;
	else
		return 1;
}

int GetBCol(int b)
{
	if (b == 0)
		return 0;
	else
		return 1;
}

第二步:AND 的表格

bool IsAnd(int a, int b, int result)
{
	int tableAnd[2][2] =
	{
		 { 0, 0},
		 { 0, 1}
	};

	int nARow = GetARow(a);
	int nBCol = GetBCol(b);

	if (tableAnd[nARow][nBCol] == result)
		return true;
	else
		return false;
}

第三步:OR 的表格

bool IsOr(int a, int b, int result)
{
	int tableOr[2][2] =
	{
		 { 0, 1},
		 { 1, 1}
	};

	int nARow = GetARow(a);
	int nBCol = GetBCol(b);

	if (tableOr[nARow][nBCol] == result)
		return true;
	else
		return false;
}

第四步:XOR 的表格

bool IsXor(int a, int b, int result)
{
	int tableXor[2][2] =
	{
		 { 0, 1},
		 { 1, 0}
	};

	int nARow = GetARow(a);
	int nBCol = GetBCol(b);

	if (tableXor[nARow][nBCol] == result)
		return true;
	else
		return false;
}

完整程式碼

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

bool IsAnd(int a, int b, int result);
bool IsOr(int a, int b, int result);
bool IsXor(int a, int b, int result);

int GetARow(int a);
int GetBCol(int b);

int main()
{
	//處理輸入資料
	string input;
	getline(cin, input);
	stringstream delim(input);
	string pch;

	int a;
	getline(delim, pch, ' ');
	a = stoi(pch);

	int b;
	getline(delim, pch, ' ');
	b = stoi(pch);

	int result;
	getline(delim, pch, ' ');
	result = stoi(pch);

	//題目處理
	bool bAnd = IsAnd(a, b, result);
	bool bOr = IsOr(a, b, result);
	bool bXor = IsXor(a, b, result);

	if (bAnd)
		cout << "AND" << endl;

	if (bOr)
		cout << "OR" << endl;

	if (bXor)
		cout << "XOR" << endl;

	if (!bAnd && !bOr && !bXor)	//如果全部都沒有
		cout << "IMPOSSIBLE" << endl;

	system("pause");
	return 0;
}

bool IsAnd(int a, int b, int result)
{
	int tableAnd[2][2] =
	{
		 { 0, 0},
		 { 0, 1}
	};

	int nARow = GetARow(a);
	int nBCol = GetBCol(b);

	if (tableAnd[nARow][nBCol] == result)
		return true;
	else
		return false;
}
bool IsOr(int a, int b, int result)
{
	int tableOr[2][2] =
	{
		 { 0, 1},
		 { 1, 1}
	};

	int nARow = GetARow(a);
	int nBCol = GetBCol(b);

	if (tableOr[nARow][nBCol] == result)
		return true;
	else
		return false;
}
bool IsXor(int a, int b, int result)
{
	int tableXor[2][2] =
	{
		 { 0, 1},
		 { 1, 0}
	};

	int nARow = GetARow(a);
	int nBCol = GetBCol(b);

	if (tableXor[nARow][nBCol] == result)
		return true;
	else
		return false;
}

int GetARow(int a)
{
	if (a == 0)
		return 0;
	else
		return 1;
}

int GetBCol(int b)
{
	if (b == 0)
		return 0;
	else
		return 1;
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *