C++编程实现求取三个变量的合式公式的真值表,输入变量个数为三个的合式公式,变量依次为P、Q、R,按行依次输出原子变元赋值及合式公式真值,赋值之间以空格分隔
时间: 2024-02-03 17:14:15 浏览: 80
以下是C++实现代码:
```c++
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
bool evaluate(char op, bool p, bool q, bool r) {
bool result = false;
switch (op) {
case '&':
result = p && q && r;
break;
case '|':
result = p || q || r;
break;
case '^':
result = (p ^ q) ^ r;
break;
case '!':
result = !p;
break;
default:
cout << "Invalid operator: " << op << endl;
break;
}
return result;
}
void print_table(string formula) {
cout << "P Q R " << formula << endl;
for (int i = 0; i < pow(2, 3); i++) {
bool p = i & 0b100;
bool q = i & 0b010;
bool r = i & 0b001;
bool result = evaluate(formula[0], p, q, r);
for (int j = 1; j < formula.length(); j += 2) {
result = evaluate(formula[j], result, evaluate(formula[j + 1], p, q, r), r);
}
cout << p << " " << q << " " << r << " " << result << endl;
}
}
int main() {
string formula;
cout << "Enter a formula with P, Q, R as variables and &, |, ^, ! as operators: ";
getline(cin, formula);
print_table(formula);
return 0;
}
```
代码中的 `evaluate` 函数用于计算单个操作符的真值,而 `print_table` 函数则用于输出真值表。在主函数中,我们首先让用户输入合式公式,然后调用 `print_table` 函数输出真值表。
以下是一个程序运行的例子:
```
Enter a formula with P, Q, R as variables and &, |, ^, ! as operators: P & Q | !R
P Q R P & Q | !R
0 0 0 1
0 0 1 1
0 1 0 0
0 1 1 0
1 0 0 1
1 0 1 1
1 1 0 0
1 1 1 0
```
输出的第一行是公式本身,接下来依次输出变量赋值及公式的真值。
阅读全文