【问题标题】:Program that finds the biggest space between two appears of the entered character查找输入字符的两次出现之间的最大间隔的程序
【发布时间】:2015-04-16 07:20:13
【问题描述】:

所以我做了一个程序,但它不能正常工作,我想看看是否有人可以帮助我。也许连这个想法都不对,我不确定。 它应该找到所提供字符的两次出现之间的最大间隔,并将其打印出来,或者如果该字符没有出现至少 2 次,则打印 0。

 #include <stdio.h>
main()

{

int i=0,k=0,max,a[50],j;
char n,c;

printf("Insert the character:\n");

scanf("%c",&n);

while ((c=getchar()) != EOF)
{
 if (c==n)
        {
         c=getchar();
         while (c != n)
                 {
                  k++;
                  c=getchar();
                 }
         a[i]=k;
         k=0;
         i++;
        }
}



max=a[0];

for (j=1; j<i; j++)
        if (a[j]>max) max=a[j];



if (max>=2) printf("%d\n",max);

else printf("0\n");

}

【问题讨论】:

  • 建议:main() 应该是int main(void)
  • scanf("%d",&amp;n); 扫描一个字符?我强烈建议您在编写代码之前阅读基础知识。
  • 我对代码做了一些试验,忘记将扫描的类型改回 char 以及 n,c 变量。感谢您指出这一点,我编辑了它。

标签: c character


【解决方案1】:
  1. 初始化maxa[0]
  2. 在内部 while 循环中检查 EOF

    #include <stdio.h>
    int main()
    {
        int i=0,k=0,max,a[50],j;
        char n,c;
        a[0] = 0;                                     // Initialize a[0]
        max  = 0;                                     // Initialize max
        printf("Insert the character:\n");
        scanf("%c",&n);
        int end_reached = 0;
        while ((c=getchar()) != EOF)
        {
            if (c==n)
            {
                c=getchar();
                while (c != n)
                {
                    if(c == EOF) {                     // Check for EOF
                        end_reached = 1;
                        break;
                    }
                    k++;
                    c=getchar();
                }
                if(!end_reached) {                     // Store k in a only if end was not reached.
                    a[i]=k;
                    k=0;
                    i++;
                }
            }
        }
        max=a[0];
        for (j=1; j<i; j++)
            if (a[j]>max)
                max=a[j];
        if (max>=2) 
            printf("%d\n",max);
        else 
            printf("0\n");
    }
    

【讨论】:

  • @MilanRakic 如果它解决了您的问题,请接受答案
猜你喜欢
  • 2020-01-19
  • 2014-08-15
  • 2021-04-29
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
  • 2020-09-29
  • 1970-01-01
相关资源
最近更新 更多