内容:
针对给定的包含任意个变量的真值表,编程实现用真值表法求取其所对应的主析取范式和主合取范式。
要求:
能够掌握通过真值表求取相应主析取和主合取范式的方法及原理。
代码:
/* * Author: Tob_yuhong * Function: 针对给定的包含任意个变量的真值表,编程实现用真值表法求取其所对应的主析取范式和主合取范式。 * 运行环境:Code::Blocks 13.12 */ #include <iostream> #include <cstdio> #include <cstdlib> #include <vector> #include <cstring> #include <cmath> #include <fstream> using namespace std; const int LEN = 140 + 10; //定义数组长度 char arr[LEN]; //用来存放2^n次方个字符,n表示变量个数 int brr[LEN][4+10]; //brr用来存放真值表 int beg = 80; //字符P对应的ASCII码 int sta1 = 0, sta2 = 0; //sta1表示真值为T的个数,sta2表示真值为F的个数 int main() { // freopen("datain.txt", "r", stdin); memset(brr, 0, sizeof(brr)); int num; //变量个数 cout << "请输入变量个数 : "; cin >> num; cout << endl; int sum = pow(2, num); //2^n cout << "请输入"<< sum << "个字符(用T 或 F表示) : "; for(int i = 1; i <= sum; i++) { cin >> arr[i]; if(arr[i] == 'T') sta1++; else sta2++; } cout << endl; //处理真值表 int cnt1 = 0, cnt2 = 1; for(int i = sum-1; i >= 0; i--) { cnt1 = 0; int val=i; while(cnt1 < num) { cnt1++; brr[cnt2][cnt1] = val%2; val = val/2; } cnt2++; } cout << "输出公式对应的真值表 : " << endl; for(int i = 1; i <= num ;i++) { cout << char(beg++) << " "; } cout << 'A'; cout << endl; cout << "———————————" << endl; beg = 80; for(int i = 1; i <= sum; i++) { for(int j = num; j >= 1; j--) { if(brr[i][j] == 1) cout << 'T' << " "; else cout << 'F' << " "; } cout << arr[i]; cout << endl; } cout << endl; int k = 0; cout << "输出主析取范式:" << endl; for(int i = 1; i <= sum; i++) { if(arr[i] == 'T') { k++; cout << '('; for(int j = num; j >= 1; j--) { if(brr[i][j] == 1) { cout << (char)(beg++); } else { cout << "┓" << (char)(beg++); } if(j != 1) cout << "∧"; } cout << ')'; if(k < sta1) cout << "∨"; } beg = 80; } cout << endl << endl; cout << "输出主合取范式:" << endl; for(int i = 1; i <= sum; i++) { if(arr[i] == 'F') { k++; cout << '('; for(int j = num; j >= 1; j--) { if(brr[i][j] == 0) { cout << (char)(beg++); } else { cout << "┓" << (char)(beg++); } if(j != 1) cout << "∨"; } cout << ')'; if(k < sta2) cout << "∧"; } beg = 80; } cout << endl; return 0; }
运行结果示意:
测试数据:
/*
3
T F F T F F F T
*/
版权声明:本文为博主原创文章,未经博主允许不得转载。