【问题标题】:C++ Benford's Law program.C++ 本福德定律程序。
【发布时间】:2013-10-03 16:33:28
【问题描述】:

所以我必须编写一个程序来 => 分析三个不同的数据文件,并尝试确认本福德定律。您将创建一个控制台应用程序,该应用程序打开每个文件,计算以“1”、“2”、“3”等开头的值的数量,然后输出每个数字的百分比。

我想我搞砸了,但我在 Dev C++ 中不断收到错误。

int analyzeData(string fname) {
    ifstream infile(string fname);
    int tmp,count = 0;
    float percents[9];
    int nums[9] = { 0 };
    if(!infile.good())
        return 1;
    while(!infile.eof())
    {
        infile >> tmp;
        tmp = first(tmp);
        if(tmp > 0)
        {
            nums[tmp - 1] ++;
            count++;
        }
    }

是说'good'、'eof'和'infile'是非类类型? 我不知道那是什么意思! 帮助将不胜感激!谢谢!

【问题讨论】:

  • 我的克星eof()我们又见面了!

标签: c++ benfords-law


【解决方案1】:

首先

ifstream infile(string fname);

应该是

ifstream infile(fname);

您的版本是函数原型,而不是变量声明。

其次,这是循环到文件末尾的错误方式

while (!infile.eof())
{
    infile >> tmp;
    ...
}

这是正确的方法

while (infile >> tmp)
{
    ...
}

这一定是我们在这里看到的最常见的错误。 eof 并没有按照你的想法去做,任何让你写 while (!infile.eof()) 的人都是错误的。

最后first(tmp) 不是从整数中获取第一个数字的正确方法。你必须比那更努力一点。

【讨论】:

    【解决方案2】:

    不是将输入读取为整数,而是将行读取为字符串,从字符串中获取第一个数字。或者您可以读取为整数,然后将 tmp 除以 10,直到结果为

    让您的生活更轻松,并将数字用作数组的索引。您需要能够索引值 1 - 9,因此您需要将数组声明得更大一些。百分比同上。

    int nums[9] = { 0 };  // works, but do less work
    float percents[9];
    
    int nums[10] = { 0 }; // do this, then you can us the digit to index nums[]
    float percents[10];
    

    你不需要 tmp > 0 的守卫,因为你有空间容纳所有 10 个数字,

    //if( tmp > 0 )
    //{
    ...
    //}
    

    你不需要从 tmp 中减去一个,

    int analyzeData(string fname)
    {
        ifstream infile(fname);
        int tmp,count = 0;
        float percents[10];
        int nums[10] = { 0 };
        if(!infile.good())
            return 1;
        while(infile >> tmp)
        {
            tmp = first(tmp);
            {
            nums[tmp] ++;
            count++;
            }
        }
        if(count<1) count=1; //avoid division by zero
        for( tmp=1; tmp<10; ++tmp )
            cout<<tmp<<":"<<nums[tmp]<<",pct:"<<(nums[tmp]*1.0)/count<<eol;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多