要求:
输入真值表(1/0),输出相应的主析取范式和主合取范式。
#include<iostream>
#include<math.h>
using namespace std;
int Value[10000][10000];
char Variable[7]={'-','A','B','C','D','E','F'};
class Form
{
public:
Form(int nn){n=nn; k=pow(2,nn);}//构造函数
void Form_Input();//真值表输入
void Form_Output();//真值表输出
void CNF_Output();//合取范式输出
void DNF_Output();//析取范式输出
private:
int n;//n为变量的个数
int k;//k为大、小项个数
};
void Form::Form_Input()
{
cout<<"Please input the value(1/0):"<<endl;
for(int i=0;i<k;i++)
{
cin>>Value[i][0];//输出合式公式的真值 P Q R 开始
}
int col=0;
while(k/2) //构建真值表 对数组进行复制 1 0
{
k=k/2; //k的值不能改变 代表了循环次数
col++;//列数 //每一次从新的一列开始复制
int value=0;
int i=0;
for(;i<pow(2,n);i++)
{
if(value==1&&!(i%k)) value=0;
else if(value==0&&!(i%k)) value=1;
Value[i][col]=value;
}
}
k=pow(2,n);//k复位
}
void Form::Form_Output()
{
cout<<"the value is:"<<endl;
for(int j=0;j<n+1;j++)//输出变元
{
cout<<Variable[j]<<" ";
if(j==n) cout<<endl;
}
for(int i=0;i<k;i++)//输出Value数组
for(int j=0;j<n+1;j++)
{
cout<<Value[i][j]<<" ";
if (j==n) cout<<endl;
}
}
void Form::CNF_Output()
{
cout<<"CNF:"<<endl;
int count=-1;//需要输出的符号个数
for(int t=0;t<k;t++) if(Value[t][0]==1) count++;
for(int i=0;i<k;i++) //输出每一行的大项
{
if(Value[i][0]==1) //需要输出的项
{
for(int j=1;j<=n;j++)
{
if(!Value[i][j])
cout<<"┐";
cout<<Variable[j];
if(j<n) cout<<"∨";
}
if(i<k&&count)
{
cout<<" ∧ ";
count--;
}
}
}
cout<<endl;
}
void Form::DNF_Output()
{
cout<<"DNF:"<<endl;
int count=-1;//需要输出的符号个数
for(int t=0;t<k;t++) if(Value[t][0]==0) count++;
for(int i=0;i<k;i++) //输出每一行的小项
{
if(Value[i][0]==0) //需要输出的项
{
for(int j=1;j<=n;j++)
{
if(!Value[i][j])
cout<<"┐";
cout<<Variable[j];
if(j<n) cout<<"∧";
}
if(i<k&&count)
{
cout<<" ∨ ";
count--;
}
}
}
cout<<endl;
}
void main()
{
int n;
cout<<"Please input Variable num:";
cin>>n;
Form A(n);
A.Form_Input();
A.Form_Output();
A.CNF_Output();
A.DNF_Output();
}