c - 最大值始终设置为 8

标签 c

我正在编写一个接受输入的程序,然后打印其中每个字母出现频率的最大值。对于这个程序,我决定只接受这 5 个字母的输入:a、b、c、d 和 e。程序是这样进行的。

#include <stdio.h>

int main(){
    int i, c , nchar[5];
    int maxvalue;

   for(i=0;i<5;i++){
    nchar[i]=0;
   }

    /*COLLECTING AND SETTING THE DATA*/
    while((c=getchar())!=EOF){
        if (c=='a')
            nchar[0]++;

        else if (c=='b')
            nchar[1]++;

        else if (c=='c')
            nchar[2]++;

        else if (c=='d')
            nchar[3]++;

        else if (c=='e')
            nchar[4]++;

    }
    printf("%d",setMax(nchar,maxvalue));


}
int setMax(int a[5], int maxv){
    if ( a[0]> a[1] &&  a[0]> a[2] &&  a[0]>a[3] &&  a[0]> a[4])
        a[0]=maxv;

    else if ( a[1]> a[0] && a[1]> a[2] && a[1]> a[3] && a[1]> a[4])
        a[1]=maxv;

    else if ( a[2]> a[0] && a[2]> a[1] && a[2]> a[3] && a[2]> a[4])
        a[2]=maxv;

    else if ( a[3]> a[0] && a[3]> a[2] && a[3]> a[1] && a[3]> a[4])
        a[3]=maxv;

    else if ( a[4]> a[0] && a[4]> a[2] && a[4]> a[3] && a[4]> a[1])
        a[4]=maxv;

        return maxv;

}

现在,例如我将输入写为“aaabc”,它应该打印值 3,因为最大频率是字母“a”,即 3。但是,它打印值 8。不仅是这个输入,但是我作为输入写的任何东西,它总是打印 8。有人能告诉我我犯了什么错误吗?

最佳答案

你的逻辑倒退了。

代替

if ( a[0]> a[1] &&  a[0]> a[2] &&  a[0]>a[3] &&  a[0]> a[4])
    a[0]=maxv;

你需要

if ( a[0]> a[1] &&  a[0]> a[2] &&  a[0]>a[3] &&  a[0]> a[4])
    maxv = a[0];

总体改进

将函数 setMax() 的名称更改为 getMax() 并将其签名更改为:

int getMax(int a[5]);

将用法更改为:

printf("%d", getMax(nchar);

并将实现更改为:

int getMax(int a[5]){

   int maxv = 0;
    if ( a[0]> a[1] && a[0]> a[2] &&  a[0]>a[3] &&  a[0]> a[4])
        maxv = a[0];

    else if ( a[1]> a[0] && a[1]> a[2] && a[1]> a[3] && a[1]> a[4])
        maxv = a[1];

    else if ( a[2]> a[0] && a[2]> a[1] && a[2]> a[3] && a[2]> a[4])
        maxv = a[2];

    else if ( a[3]> a[0] && a[3]> a[2] && a[3]> a[1] && a[3]> a[4])
        maxv = a[3];

    else if ( a[4]> a[0] && a[4]> a[2] && a[4]> a[3] && a[4]> a[1])
        maxv = a[4];

    return maxv;
}

更新

getMax() 的更新版本修复了两个值相等时的问题。

int getMax(int a[5])
{
   if ( a[0] >= a[1] && a[0] >= a[2] &&  a[0] >= a[3] &&  a[0] >= a[4] )
      return a[0];

   // a[0] is not the max. it has has be a[1], a[2], a[3], or a[4]
   if ( a[1] >= a[2] && a[1] >= a[3] && a[1] >= a[4] )
      return a[1];

   // Similarly, the max has to be a[2], a[3], or a[4]
   if ( a[2] >= a[3] && a[2] >= a[4] )
      return a[2];

   // Similarly, the max has to be a[3] or a[4]
   if ( a[3] >= a[4] )
      return a[3];

   // At this point, a[4] has to be the max value.
   return a[4];
}

关于c - 最大值始终设置为 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30872946/

相关文章:

c - pthread 如何返回最快的结果并终止较慢的结果?

c - c BST 中的段错误(核心转储)

c++ - 在递归下降解析器中使用第一集

c++ - 提高给定字符串的所有排列的时间复杂度

c# - 动态端口转发 libssh C

c - 如何创建一个程序,要求用户输入 "up to"20 个整数,并使用传递给函数的参数来输出最大值、最小值和平均值?

检查单链表中的回文

c - 使用 libavcodec 保存 H.264 编码图像

c - 在其他结构中重新分配数组结构

比较 C 中的单词数组