#include<math.h>
#include<iomanip.h>
#include<stdlib.h>
class T
{
public:
T(){}
~T()
void Create()
void Coutpxj()
void Coutk()
void Coutz()
void Print()
protected:
int n
double *p
double *pxj
int *k
double *mz
}
void T::Create()
{
cout<<"请输入信源符号个数:"
cin>>n
p=new double[n]
cout<<"请分别输入这"<<n<<"个概率:\n"
for(int i=0i<ni++)cin>>p[i]
pxj=new double[n]
k=new int[n]
mz=new double[n]
double sum=0.0
for(i=0i<ni++)sum+=p[i]
if(sum!=1.0)
throw 1
else
{
for(i=0i<ni++){
int k=i
for(int j=i+1j<nj++)
if(p[k]<p[j]) k=j
double m=p[i]
p[i]=p[k]
p[k]=m
}
}
}
T::~T()
{
delete p
delete pxj
delete k
delete mz
}
void T::Coutpxj()
{
pxj[0]=0
for(int i=1i<ni++)
{
pxj[i]=0
for(int j=0j<ij++)
pxj[i]+=p[j]
}
}
void T::Coutk()
{
for(int i=0i<ni++)
{
double d=(-1)*(log(p[i])/log(2))
if(d-(int)d>0)k[i]=(int)d+1
elsek[i]=(int)d
}
}
void T::Print()
{
cout<<"Xi"<<setw(8)<<"P(xi)"
<<setw(8)<<"Pa(xj)"
<<setw(8)<<"Ki"
<<setw(8)<<"码字"
<<endl
for(int i=0i<ni++)
{cout<<"X"<<i+1
<<setw(8)<<setprecision(2)<<p[i]
<<setw(8)<<setprecision(2)<<pxj[i]
<<setw(8)<<k[i]<<""
mz[i]=pxj[i]
for(int j=0j<k[i]j++)
{
if(2*mz[i]-1>=0)
{
cout<<1
mz[i]=2*mz[i]-1
}
else
{
cout<<0
mz[i]=2*mz[i]
}
}
cout<<endl
}
double K=0.0,H=0.0,Y
for(i=0i<ni++)
{
K+=(double)p[i]*k[i]
H+=(-1)*p[i]*(log10(p[i])/log10(2.0))
}
Y=H/K
cout<<"平均码长:"<<K<<endl
cout<<"信源熵:"<<H<<endl
cout<<"编码效率:"<<Y<<endl
}
void main()
{
T tint e
try
{
t.Create()
t.Coutpxj()
t.Coutk()
t.Print()
}
catch(int e)
{if(e==1) cout<<"输入错误,请重新运行"}
}
这个是c++版本的,希望对你有用
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)