我试图找到任何给定文件的熵。但是,当我运行我的程序时,总是给出3.00000作为答案。我有一段时间没有使用C,但我不确定我在哪里出错。我现在摆弄了几个小时。任何提示都会很棒,谢谢!计算熵C
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define SIZE 256
int entropy_calc(long byte_count[], int length)
{
float entropy;
float count;
int i;
/* entropy calculation */
for (i = 0; i < SIZE; i++)
{
if (byte_count[i] != 0)
{
count = (float) byte_count[i]/(float) length;
entropy += -count * log2f(count);
}
}
return entropy;
}
int main(int argc, char **argv)
{
FILE *inFile;
int i;
int j;
int n; // Bytes read by fread;
int length; // length of file
float count;
float entropy;
long byte_count[SIZE];
unsigned char buffer[1024];
/* do this for all files */
for(j = 1; j < argc; j++)
{
memset(byte_count, 0, sizeof(long) * SIZE);
inFile = fopen(argv[j], "rb"); // opens the file given on command line
if(inFile == NULL) // error-checking to see if file exists
{
printf("Files does not exist. `%s`\n", argv[j]);
continue;
}
/* Read the whole file in parts of 1024 */
while((n = fread(buffer, 1, 1024, inFile)) != 0)
{
/* Add the buffer to the byte_count */
for (i = 0; i < n; i++)
{
byte_count[(int) buffer[i]]++;
length++;
}
}
fclose(inFile);
float entropy = entropy_calc(byte_count, length);
printf("%02.5f \t%s\n", entropy, argv[j]);
}
return 0;
}
在'entropy_calc'内,'entropy'没有被初始化。 – AlexD 2014-09-23 00:20:49
编译所有的警告和调试信息('gcc -Wall -g') - 应该给你一个关于你的bug的良好警告。 **使用调试器**('gdb') – 2014-09-23 00:21:31
我没有看到你在'main'中初始化'length'的位置。您需要检查所有变量,并确保它们在使用之前被初始化。一个好的编译器会警告你。 – user3386109 2014-09-23 00:23:51