c语言错误编号怎么看,我写的C语言霍夫曼编码,发现算法有问题,请帮忙改一下...
我写的C语言霍夫曼编码,发现算法有问题,请帮忙改一下0
#include "stdio.h"
#include "string.h"
#define TYPE struct huffman
/*定义结构体*/
TYPE
{
char name;
float p;
char code;
TYPE *left;
TYPE *right;
TYPE *root;
};
/*定义全局变量*/
TYPE tmp;
int len;
float sum;
char encode[100];
/*输入函数*/
void input(TYPE *huff)
{
int i;
printf("\nPleae input how many number you'll type in:");
scanf("%d",&len);
getchar();
printf("Please input the name:");
/*输入事件名*/
for(i=0;i
{
scanf("%c",&huff[i].name);
getchar(); /*防止下步输入读取空字符*/
}
/*输入事件概率*/
printf("Please input the numbers div with space:");
for(i=0,sum=0;i
{
scanf("%f",&huff[i].p);
getchar();
sum+=huff[i].p;
huff[i].code='\0';
huff[i].root=NULL;
huff[i].left=NULL;
huff[i].right=NULL;
}
}
/*按概率给结构体从大到小排序*/
void queue(TYPE *huff)
{
int i,j;struct huffman temp;
for(j=0;j
{
for(i=0;i
if(huff[i].p
{
temp=huff[i];huff[i]=huff[i+1];huff[i+1]=temp;
}
}
}
/*输出结构体名,及其概率*/
void output(TYPE *huff)
{
int i;
for(i=0;i
printf("%c:%3.3f\t",huff[i].name,huff[i].p);
printf("\n");
}
/*霍夫曼编码*/
void code(TYPE *huff)
{
TYPE s1,s2;
int i,j,t,s;
s1.p=huff[0].p;t=0;
s2.p=huff[0].p;s=0;
for(i=0;i
{
if(huff[i].root!=NULL) continue;
if(huff[i].p<=s1.p||huff[i].root==NULL)
{
s1.p=huff[i].p;t=i;
}
}
for(j=0;j
{
if(huff[j].root!=NULL||j==t) continue;
if(huff[j].p<=s2.p||j!=t||huff[j].root==NULL)
{
s2.p=huff[j].p;s=j;
}
}
huff[len].p=s1.p+s2.p;
huff[t].root=&huff[len];
huff[s].root=&huff[len];
huff[len].left=&huff[t];
huff[len].right=&huff[s];
huff[len].root=NULL;
huff[t].code='0';
huff[s].code='1';
huff[len].name='\0';
len++;
}
/*获得编码*/
void getcode(TYPE *huff,int i)
{
char a;
int l,j;
tmp=huff[i];
for(j=0;tmp.root!=NULL;j++)
{
encode[j]=tmp.code;
tmp=*(tmp.root);
}
encode[j]='\0';
l=strlen(encode);
for(j=0;j
{
a=encode[j];encode[j]=encode[l-j-1];encode[l-j-1]=a;
}
}
/*主函数*/
void main()
{
TYPE huff[100];
int m,i,j;
len=0,sum=0;
input(huff);
m=len;
printf("%d,%3f",len,sum);
for(;sum!=1;) /*如果输入错误,提示重新输入*/
{
printf("\nSorry! the numbers you typed in are illegal!Pleaese input again:\n");
input(huff);
}
printf("the numbers you typed in are:\n");
output(huff);
queue(huff);
printf("the numbers from max to min:\n");
output(huff);
for(i=0;i
code(huff);
for(i=0;i
{
printf("%c,%3.3fcode:%c\t",huff[i].name,huff[i].p,huff[i].code);
}
printf("\n");
for(i=0;i
{
getcode(huff,i);
printf("name:%c,code:%s\t",huff[i].name,encode);
}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
