1、设计思想
为了设计的方便,我们需要在这个程序里设计一个结构体,以用来存储信源符号、信源符号概率等参数,将每一组参数看成一个结构体来看待,这样我们就可以随时地调用。
2、设计流程
主函数部分,我们先接收要输入的信源符号个数,再接收每个信源符号的名称以及他的概率。
主函数设计好后,我们将各功能的函数分成几个模块来写,第一个是排序函数,如果你坚持从大到小输入则可以不用写;第二个函数计算前几个符号概率的累加;第三个函数计算每个符号码字长度;第四个函数将累加概率转换为二进制。各个函数分工完成的话,问题就变得简单多了。
我们来简单绘制一下其流程图:
扫描二维码关注公众号,回复:
148641 查看本文章
3、设计程序
#include <stdio.h> #include <math.h> #include <string.h> int i,j,n,k,b; float a; char bitw[20]; struct shan { char s[20]; float p; float pa; float l_f; int l; char w[20]; }data[12]; void sequ(struct shan x[],int n) { struct shan temp; for(i=0;i<n;i++) for(j=i;j<n;j++) { if(x[i].p<x[j].p) { temp=x[j]; x[j]=x[i]; x[i]=temp; } } } void countpa(struct shan x[],int n) { a=0; x[0].pa=0; for(i=0;i<n;i++) { a+=x[i].p; x[i+1].pa=a; } } void count_l(struct shan x[],int n) { for(i=0;i<n;i++) { x[i].l_f=-log(x[i].p)/log(2); if((x[i].l_f-(int)x[i].l_f)>0) { x[i].l=(int)x[i].l_f+1; } else x[i].l=(int)x[i].l_f; } } void covbit(float d,int lc) { for(j=0;j<lc;j++) { b=(int)(d*2); bitw[j]=b+48; d=2*d-int(d*2); } } main() { printf("please input the number of symbols of source(n<=10):n="); scanf("%d",&n); printf("please input the the source symbols and their probabilities\n"); for(i=0;i<n;i++) { scanf("%s",data[i].s); } for(i=0;i<n;i++) { printf("P(%s)=",data[i].s); scanf("%f",&data[i].p); } sequ(data,n); countpa(data,n); count_l(data,n); for(i=0;i<n;i++) { covbit(data[i].pa,data[i].l); strcpy(data[i].w,bitw); } for(i=0;i<n;i++) printf("p(%s)=%f padd=%f l=%d w=%s\n",data[i].s,data[i].p,data[i].pa,data[i].l,data[i].w); }
4、设计结果
参考:https://blog.csdn.net/keyhn/article/details/5185806