c - 查找数字中最大数字的频率

标签 c loops

#include <stdio.h>

int main(void)
{
    int i=0,max=0;
    long long int n,p;
    scanf("%lld",&n);
    while(n>0)
    {
        p=n%10;
        if(p==max)
        {
            i++;
        }
        else if(p>max)
        {
            max=p;
            i=1;
        }
        n/=10;
    }
    printf("%d",i);
    return 0;
}

对于 8687557576676885 等数字,代码给出了正确的结果。但对于输入 11111111111111111111111111111111 ,它没有给出正确的结果。我在这个网站上看到过类似的问题,但这些问题是用不同的语言编写的。我想知道大数的问题出在哪里。

谢谢...

注意:如果有人能提供替代解决方案,那将会很有帮助。我还是个新手,所以这会帮助我更深入地理解事情。

最佳答案

The code gives correct results for numbers like 8687557576676885 . But for the input 11111111111111111111111111111111

8687557576676885需要53位,但11111111111111111111111111111111需要104位,对于64位上的long long来说太多了

It would be helpful if anyone could give alternate solutions

不要使用scanf,而是使用fgets或类似的strtoll,您将能够通过查看errno来检测溢出

但是,在您的情况下,您不需要提取数字,只需处理字符串,例如不受任何大小的限制:

#include <stdio.h>

int main(void)
{
  int i=0,max=-1;
  int c;

  while ((c = fgetc(stdin)) && (c != EOF) && (c != '\n')) {
    if ((c < '0') || (c > '9')) {
      printf("'%c' is not a valid digit\n", c);
      return -1;
    }
    c -= '0';
    if(c==max)
    {
      i++;
    }
    else if(c>max)
    {
      max=c;
      i=1;
    }
  }
  if (max != -1)
    printf("%d times %d\n",i, max);
  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra m.c
pi@raspberrypi:/tmp $ ./a.out
8687557576676885
4 times 8
pi@raspberrypi:/tmp $ ./a.out
111111111111111111111111111111111111111111
42 times 1

关于c - 查找数字中最大数字的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56405484/

相关文章:

python - 在循环内组合 numpy 数组

regex - vbscript 中检查字符串是否包含多个单词/短语列表中的单词/短语的最快方法

loops - Arduino循环中的奇怪行为

char** 分配以及如何存储值

c - 为链接器指定外部存储器

c - 阅读列表

Javascript,比较数组中的元素,如果为 true 则执行函数

c - 如何使用结构来表示复数

c - C 中的局部和外部变量命名约定

c - 如何从C中的最小堆中删除第一个元素?