费诺编码C语言实现

// This is a Fano coding program! ;
// Input the probability and then get the Fano code;

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
static char p[11][10];
static int flag1=0;
static int ncount1;

//...............main........................

void main()
{
	void Fano(int m,int n,float y[10]);
	int i,j,flag,ncount;
	float a[11],temp,s=0.0,code_length=0.0;
	flag=0;
	do
	{
		printf("Note: Quit the program when ncount=0 !!!\n");
		printf("Please input the amount of probabilities,ncount:\n");
		scanf("%d",&ncount);
		if(ncount==0) exit(0);
		while(ncount<0)
		{
			printf("Please input the positive integer! Try again!\n");
			printf("Note: Quit the program when ncount=0 !!!\n\n");
			printf("Please input the amount of probabilities,ncount:\n");
			scanf("%d",&ncount);
			if(ncount==0) exit(0);
		}
		while(flag==0)
		{
			flag=1;
			printf("Please all probability!\n");
			for(i=1;i<ncount+1;i++)
			{
				scanf("%f",&a[i]);
				if((a[i]<1e-10)||(a[i]-1>1e-10))
					{printf("Please input the number which is between 0 and 1\n");flag=0;}
				else s=s+a[i];
				if(s-1>1e-10)
					{ printf("Please make sure that the sum of all numbers is 1 !!\n");flag=0;s=0;}
	
			}
		}
		for(i=1;i<ncount;i++)
			for(j=i+1;j<ncount+1;j++)
				if(a[i]<a[j]){temp=a[i];a[i]=a[j];a[j]=temp;}
		Fano(1,ncount,a);
		printf("\n\nThe fano code is:\n\n");
			printf("Probability\t\tFano code\t\tcode length\n\n");
		for(i=1;i<ncount+1;i++)
		{
		
			printf("  %.3f\t\t\t",a[i]);
			printf("%s",p[i]);
			printf(" \t\t\t %d\n",strlen(p[i]));
			code_length=code_length+strlen(p[i]);
		}
		printf("\n The average code length is :%.3f \n",code_length/ncount);
		printf("\n\n");
		flag1=0;
		code_length=0.0;

	}while(1);
	exit(0);
}



//..............Fano sub-program..............
void Fano(int m,int n,float y[11])
{  
    int j,k;
    float sum=0.0,s=0.0,s1,z[11];
	flag1++;
	if(flag1==1) 
		ncount1=n;
    if(m==n) 
	{return;}
   for(j=1;j<ncount1+1;j++)
   z[j]=y[j];
  for(j=m;j<=n;j++)
       sum=sum+z[j];
         k=m;
     do{ s1=s;
	 s=s+y[k++];
       }while(s<=sum-s);
   if((sum-2*s1)<=(2*s-sum))k--;
 for(j=m;j<k;j++)
       strcat(p[j],"0");
     for(j=k;j<=n;j++)
       strcat(p[j],"1");
     Fano(m,k-1,y);
     Fano(k,n,y);
}










  • 4
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值