#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
double* cal1(double* all1)
{
int t,count=0;
ifstream srcFile("in.txt", ios::in);
if (!srcFile)
{
cout << "error opening source file." << endl;
return 0;
}
char x;
while (srcFile >> x)
{
t = x - 'a' ;
count++;
if (t >= 0 && t <= 25)
all1[t]++;
else
all1[26]++;
}
all1[27] =count ;
srcFile.close();
/* for (t = 0; t <= 26; t++)
{
cout << all1[t] / all1[27]<<endl;
}
cout << all1[27] << endl;*/
return all1;
}
double finalcal1(double* all)
{
int t;
double p,cal1=0;
for (t = 0; t <= 26; t++)
{
p = (all[t] / all[27]);
all[t] = p * log(p);
}
for (t = 0; t <= 26; t++)
{
cal1 -= all[t];
}
return cal1;
}
int main()
{
double *all =new double[28]; //1
double t;
all = cal1(all);
t = finalcal1(all);
cout << t << endl;
delete[] all;
return 0;
}
enter code here
我没有从结果中得到一个数字,而是得到了一个甚至不是数字的“ -nan。(ind)”。此外,当我将数字从标记1更改为* all = new double [27]时,应该会显示错误或错误。
答案 0 :(得分:0)
double *all =new double[28];
您可能想将所有这些值初始化为零,因为否则,它们将具有任意值。
而且,如果这些任意值由任何NaN
个项目组成,那么当您向其中添加内容或除以某个计数时,这些内容就会传播。
类似这样的技巧可以解决问题:
double *all = new double[28]();
您可能还想考虑以下可能性:实际上并未为log(x)
的所有值(例如零或负值)定义x
-可能是另一个 获得NaN
的方式。