提问者:小点点

为什么我的循环没有返回正确的答案?


我想不出来。我的代码有什么问题?我是编程新手。

程序所需输出:编写一个C++程序,使用循环查找数组中出现最大值的字符。

我的代码:

#include <string.h>
using namespace std;

void FindMaxChar(char Word[])
{
    int count = 0;
    int max = 0;
    char index = 0;
    int length = strlen(Word);

    for (int i = 0; i < length; i++)
    {
        index = Word[i];
        for (int j = 0; j < length; j++)
        {
            if (index == Word[j])
            {
                count++;
            }
        }
        if (count > max)
        {
            max = count;
            index = Word[i];
        }
    }
    cout << index << " is repeating " << max << " times.";
}

int main()
{
    char Word[100] = {0};
    cout << "Enter the Word = ";
    cin.get(Word,100);
    FindMaxChar(Word);
}

我的输出:

Enter the Word = caaar
r is repeating 11 times.

共1个答案

匿名用户

您从不在每个循环中重置。所以您继续递增它,但从不清除它。

添加到外部for循环的开头:

for (int i = 0; i < length; i++)
{
    count = 0; // Reset counter

您还尝试将用于两个不同的目的。你既用它来存储你正在查看的当前字符(不是索引,你这样命名有点让人困惑),又用它来存储你见过最多的字符(仍然不是索引,也让人困惑)。

相反,这里需要另一个变量。

还要注意,如果您将声明为,它只能保存长度为99的c-string(为空字符留出空间)。所以你的cin实际上应该是:

cin.get(Word, 99);