最近老师硬是要交作业,所以出于无奈胡乱写写,还望各位不吝赐教。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream.h>
#include <string.h>
int num; //输入的字符个数
int i,j;
float temp_p; //过渡概率
char temp_char[20];//过渡字符
char code[200]; //编译出来的码字
struct shannon_code{
char m_in[20]; //输入的字符
float m_p; //输入的字符的概率
float m_addp; //累加概率
int m_length; //需要的码长
}shannon[30];
char *m_code; //输出的码字
void sequence() //按概率从大到小排序
{
for (i=1;i<=num;i++)
{
for (int j=i+1;j<=num;j++)
{
if(shannon[j].m_p>=shannon[i].m_p)
{
temp_p=shannon[i].m_p;
shannon[i].m_p=shannon[j].m_p;
shannon[j].m_p=temp_p;
strcpy(temp_char,shannon[i].m_in);
strcpy(shannon[i].m_in,shannon[j].m_in);
strcpy(shannon[j].m_in,temp_char);
}
}
}
}
void code_length() //计算所需码长
{
for (i=1;i<=num;i++)
{
int temp=(int)(log10(1.0/shannon[i].m_p)/log10(2));
if (temp-log10(1.0/shannon[i].m_p)/log10(2)!=0)
shannon[i].m_length=temp+1;
else shannon[i].m_length=temp;
}
}
void shannoncode() //进行香农编码
{
float temp_addp; //过渡累加概率
if(i==1)
shannon[i].m_addp=0;
else
shannon[i].m_addp=shannon[i-1].m_addp+shannon[i-1].m_p;
temp_addp=shannon[i].m_addp;
for (j=0;j<shannon[i].m_length;j++)
{
temp_addp=temp_addp*2;
if (temp_addp>=1)
{
code[j]=(int)temp_addp+48;
temp_addp=temp_addp-1;
}
else
code[j]=(int)temp_addp+48;
}
code[shannon[i].m_length]='/0';
}
void main()
{
cout<<"input the numbers of message(num<30):"<<endl; //输入信源个数
cin>>num;
cout<<"input the characters and their's probability:"<<endl; //输入各个信源的概率
for (i=1;i<=num;i++)
{
cout<<"character"<<i<<": ";
cin>>shannon[i].m_in;
cout<<"probability of character"<<i<<": ";
cin>>shannon[i].m_p;
}
sequence();
cout<<"After order from big to small by probability :"<<endl; //经过从大到小的排序后排列
for (i=1;i<=num;i++)
{
cout<<shannon[i].m_in<<": "<<shannon[i].m_p<<" "<<endl;
}
code_length(); //输出各个信源编码所需要的码长
cout<<"the length of each character: "<<endl;
for (i=1;i<=num;i++)
{
cout<<shannon[i].m_in<<": "<<shannon[i].m_length<<" "<<endl;
}
cout<<"The code of character is: "<<endl; //各个信源编码后的码字
for (i=1;i<=num;i++)
{
shannoncode();
cout<<shannon[i].m_in<<": ";
for (j=0;j<shannon[i].m_length;j++)
cout<<code[j];
cout<<endl;
}
}