【问题标题】:Count Occurrences within a for loop c++在for循环c ++中计算出现次数
【发布时间】:2013-04-18 16:32:28
【问题描述】:

我是 C++ 新手,我想做的是计算一个字母与一段文本或段落一起出现的次数,并将其存储到一个称为频率数组的数组中。

下面的代码在一定程度上是有效的,如果用户键入 hello frequencyarray stores 11121,如果用户键入 aaba frequencyarray stores 1213,会发生什么情况 我不想要一个运行总数,我希望数组存储 1121 和 31。所以如果出现相同的字母,它会将 1 添加到数组中。

谢谢大卫

#include <iostream> //for cout cin
#include <string>   //for strings
#include <fstream>  //for files

using namespace std;

int main()
{       
    string text;

    int frequencyarray [26]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

    cout << "Enter Word: ";
    cin >> text;

//***************************COUNT OCCURANCES************************

    for (int i(0); i < text.length(); i++)
    {
        char c = text[i];

        c = toupper(c);
        c -= 65;

        if (c < 26 || c >=0)
        {
            frequencyarray[c]++;
            cout << frequencyarray[c];
        }
    }

    system ("pause");

return(0);

}`

【问题讨论】:

  • 你在循环中输出数组的内容不是问题吗?第一次找到字母“a”时,下一次将打印 1,以此类推。将数组转储到循环之外,您将得到正确的输出。
  • 您还应该在 if 语句中使用 &amp;&amp;。现在所有个字符都符合条件。
  • 你也可以使用c -= 'A';代替常量65

标签: c++ arrays visual-c++


【解决方案1】:

如果您不想要运行总数,请不要将 cout &lt;&lt; freqencyarray[c]; 包含在计算出现次数的循环中。

【讨论】:

    【解决方案2】:

    试试这个

    #include <iostream> //for cout cin
    #include <string>   //for strings
    #include <fstream>  //for files
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {       
        string text;
    
        int frequencyarray [26]={0};
    
        cout << "Enter Word: ";
        cin >> text;
    
    //***************************COUNT OCCURANCES************************
    
        for (int i(0); i < text.length(); i++)
        {
            char c = text[i];
    
            c = toupper(c);
            c -= 65;
    
            if (c < 26 || c >=0)
            {
                frequencyarray[c]++;
            }
        }
    
        std::for_each(std::begin(frequencyarray), std::end(frequencyarray), [](int i)
        {
             std::cout << i << ",";
        });
        std::cout << "\n";
        system ("pause");
    
    return(0);
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多