Boolean Expressions(北大MOOC程序設計與算法二 第三週測驗題)

Boolean Expressions

The objective of the program you are going to produce is to evaluate boolean expressions as the one shown next:
Expression: ( V | V ) & F & ( F | V )

where V is for True, and F is for False. The expressions may include the following operators: ! for not , & for and, | for or , the use of parenthesis for operations grouping is also allowed.

To perform the evaluation of an expression, it will be considered the priority of the operators, the not having the highest, and the or the lowest. The program must yield V or F , as the result for each expression in the input file.

輸入

The expressions are of a variable length, although will never exceed 100 symbols. Symbols may be separated by any number of spaces or no spaces at all, therefore, the total length of an expression, as a number of characters, is unknown.

The number of expressions in the input file is variable and will never be greater than 20. Each expression is presented in a new line, as shown below.

輸出

For each test expression, print "Expression " followed by its sequence number, ": ", and the resulting value of the corresponding test expression. Separate the output for consecutive test expressions with a new line.

Use the same format as that shown in the sample output shown below.

輸入樣例

( V | V ) & F & ( F| V)
!V | V & V & !F & (F | V ) & (!F | F | !V & V)
(F&F|V|!V&!F&!(F|F&V))

輸出樣例

Expression 1: F
Expression 2: V
Expression 3: V

實現代碼

#include<iostream>
#include<iomanip>
#include<string.h>
#include<cstdio>
#include<cmath>
#include<set> 
using namespace std;
void blank(){		//用來去掉空格
	char op;
	while((op=cin.peek())==' '){
			cin.get();
	}
	return;
}
int factor_value();
int expression_value(){		//與、或的計算
	int a=factor_value();
	bool more=true;
	while(more){
		char op=cin.peek();		//察看下一個字符
		blank();	//處處會有空格!!!
		if(op=='|'||op=='&'){
			cin.get();
			blank();	//處處會有空格!!!
			int b=factor_value();
			if(op=='|')	a=a|b;
			else	a=a&b;
		}
		else{
			more=false;
		}
	}
	return a;
}
int factor_value(){
	int a;
	char op=cin.peek();
	blank();	//處處會有空格!!!
	if(op=='('){
		cin.get();
		blank();	//處處會有空格!!!
		a=expression_value();
		cin.get();
	}
	else{
		if(op=='V'){
			cin.get();	
			a=1;
		}
		else if(op=='F'){
			cin.get();	
			a=0;
		}
		else if(op=='!'){
			cin.get();
			blank();	//處處會有空格!!!
			a=1^factor_value();
		}
	}
	blank();	//害怕有空格!!!
	return a;
}

int main()
{
	for(int i=1;cin.peek()!=EOF;i++){		//不知道何時纔會結束的字符
		int m=expression_value();
		if(m==1){
			printf("Expression %d: V\n",i);
		}
		else if(m==0){
			printf("Expression %d: F\n",i);
		}
		getchar();	//吃掉換行符
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章