1. 程式人生 > >離散數學真值表(c語言程式設計實現)

離散數學真值表(c語言程式設計實現)

程式碼如下:

廢話不多說:

主要利用二進位制的轉化實現 

#include <iostream>
#include <math.h>
using namespace std;
void shuru(char *p,int s);
void shuchu(char *p,int s);
void panduan(int s,int p,char *a,char b);
void shizi(char *p,int s);
void shiz(char *p,int s,char *a,char b);
char b[10]={'p','q','r','s','d','m','n','l','j','k'};
int main()
{
	int n;
	cout<<"input the value of n"<<endl;
	while(!(cin>>n))
	{
	cin.clear();
	cin.sync();
	cout << "不是數字"<<endl;
	}
	cout<<"input T or F"<<endl; 
	char a[100];
	shuru(a,n);
	cout<<"----------------------"<<endl;
	for(int i=0;i<n;i++){//根據命題數輸出命題符號 
		cout<<b[i]<<"		";
		}
	cout<<"VALUE"<<endl;
	shuchu(a,n);
	shizi(a,n);
}
void shuru(char *p,int s){
	for (int i=0;i<pow(2,s);i++)//判斷輸入的是否為F或者T,若是,存入陣列a,反之,跳過 
	{
			char h; 
			while(1)
			{
				cin>>h;
				if(h=='T' || h=='F')
				{
				p[i]=h;
				break;
				}
				else
				{
					getchar();
				}
			}
	}
}
///KZT
void shuchu(char *p,int s){
	int k=0,c[2]={0,1};
	while(k<pow(2,s))//輸出每個命題的真值 
	{
		for(int i=0;i<s;i++){
		if(int(k/pow(2,s-i-1))%2)
		cout<<"T"<<"		";
		else
		cout<<"F"<<"		"; 
		}
		cout<<p[k]<<endl;
		k++;
	}
	cout<<endl;
}
void shiz(char *p,int s,char *a,char b){
	int flag=0;
	for(int i=0;i<pow(2,s);i++)
	{
		if(p[i]==b){
		if(flag==1)
		cout<<a;
		panduan(s,i,a,b);
		flag=1;
		}
	}
	if(flag==0)
	if(b=='T')
	cout<<"0"<<endl;
	else
	cout<<"1"<<endl; 
}
void shizi(char *p,int s){
	cout<<"主析取正規化為:";
	shiz(p,s,"\\/",'T');
	cout<<endl<<"主合取正規化為:";
	shiz(p,s,"/\\",'F');
}
void panduan(int s,int p,char *a,char c){
	cout<<"(";
	if (a=="\\/")
	a="/\\";
	else if(a=="/\\")
	a="\\/";
	int flag=0;
	for(int i=0;i<s;i++){
		if(flag==1)
		cout<<a;
		if(int(p/pow(2,s-i-1))%2)
			cout<<b[i];
		else
			cout<<"非"<<b[i];
		flag=1;
		}
	cout<<")";
}

輸出如下圖: