请用c++代码编写程序求任意一个命题公式的真值表,并根据真值表求主范式
时间: 2024-05-04 09:15:57 浏览: 123
求给定命题公式的真值表并根据真值表求公式的主范式.pdf
很高兴收到您的第一个问题,以下是用C语言编写程序求任意一个命题公式的真值表,并根据真值表求主范式的代码:
```c
#include <stdio.h>
#include <math.h>
int main()
{
// 定义变量
int n, m, i, j, k, l, v, count = 0, flag;
char ch;
// 输入命题公式
char expr[100];
printf("请输入命题公式:\n");
scanf("%s", expr);
n = strlen(expr);
// 计算命题变元个数
m = 0;
for (i = 0; i < n; i++)
{
ch = expr[i];
if (ch >= 'A' && ch <= 'Z')
{
m++;
}
}
// 计算真值表行数
int row = pow(2, m);
// 定义二维数组存放真值表
int truthTable[row][m+1];
// 生成真值表
for (i = 0; i < row; i++)
{
v = i;
for (j = m-1; j >= 0; j--)
{
truthTable[i][j] = v % 2;
v /= 2;
}
}
// 计算命题公式的真值
for (i = 0; i < row; i++)
{
for (j = 0; j < n; j++)
{
ch = expr[j];
if (ch >= 'A' && ch <= 'Z')
{
k = ch - 'A';
truthTable[i][m] = truthTable[i][m] << 1 | truthTable[i][k];
}
else if (ch == '!')
{
flag = expr[j+1] >= 'A' && expr[j+1] <= 'Z';
l = flag ? expr[j+1] - 'A' : -1;
if (l == -1)
{
truthTable[i][m] = truthTable[i][m] << 1 | !truthTable[i][m-1];
}
else
{
truthTable[i][m] = truthTable[i][m] << 1 | !truthTable[i][l];
}
j = flag ? j + 1 : j;
}
else if (ch == '&')
{
truthTable[i][m] = truthTable[i][m] << 1 | (truthTable[i][m-2] & truthTable[i][m-1]);
m -= 1;
}
else if (ch == '|')
{
truthTable[i][m] = truthTable[i][m] << 1 | (truthTable[i][m-2] | truthTable[i][m-1]);
m -= 1;
}
}
printf("| %3d ", count++);
for (j = 0; j <= m; j++)
{
printf("| %d ", truthTable[i][j]);
}
printf("|\n");
}
// 根据真值表求主范式
int term[m][row], index[m], primeImplicant[row], minTerm[row], nPI = 0, nMT = 0, t, isPrime;
for (i = 0; i < m; i++)
{
for (j = 0; j < row; j++)
{
term[i][j] = truthTable[j][i];
}
}
for (i = 0; i < row; i++)
{
if (truthTable[i][m])
{
primeImplicant[nPI++] = i;
}
else
{
minTerm[nMT++] = i;
}
}
for (i = 0; i < m; i++)
{
index[i] = i;
}
do
{
for (i = 0; i < row; i++)
{
isPrime = 1;
for (j = 0; j < m; j++)
{
if (term[j][i] == 1 && index[j] == j)
{
isPrime = 0;
break;
}
}
if (isPrime)
{
for (j = 0; j < nPI; j++)
{
if ((primeImplicant[j] & i) == primeImplicant[j])
{
break;
}
}
if (j == nPI)
{
primeImplicant[nPI++] = i;
}
}
}
t = 0;
for (i = 0; i < m-1; i++)
{
if (index[i] < index[i+1])
{
t = 1;
break;
}
}
if (t == 0)
{
break;
}
for (i = m-1; i >= 1; i--)
{
if (index[i] > index[i-1])
{
break;
}
}
for (j = m-1; j >= i; j--)
{
for (l = 0; l < row; l++)
{
term[j-1][l] |= term[j][l];
}
}
for (j = index[i]-1; j >= i; j--)
{
for (l = 0; l < row; l++)
{
term[j][l] = term[j-1][l];
}
index[j+1] = index[j];
}
for (l = 0; l < row; l++)
{
term[i-1][l] &= term[i][l];
}
index[i] = index[i-1]+1;
} while (1);
printf("主范式为:\n");
for (i = 0; i < nPI; i++)
{
printf("(");
for (j = 0; j < m; j++)
{
if ((primeImplicant[i] >> j) & 1)
{
printf("%c", j+'A');
}
else if ((primeImplicant[i] >> j) & 2)
{
printf("!%c", j+'A');
}
}
printf(")");
if (i < nPI-1)
{
printf("|");
}
}
printf("\n");
return 0;
}
```
希望这个代码对您有所帮助!如果您还有其他问题,请继续提出,我会尽力回答。
阅读全文