c - 如何查找数字0-9在整数中出现的次数

标签 c ansi-c

我需要一些代码方面的帮助,因为 heahline 说我需要找到数字 0-9 在整数中出现的次数,然后像这样打印它: 300 以 10 为基数 0:2 1:0 2:0 3:1 4:0 5:0 6:0 7:0 8:0 9:0 我已经尝试过

#include <stdio.h>
#include <stdlib.h>

int main()

{

int num, div=1, rem, count=0, i;
printf("Enter Number: ");
scanf("%d", &num);
div = num;
for(i=1; i<=10; i++)
{
    div = num;
    while(div!< 0)
    {
    rem = div % 10;
    div = div / 10;


    if(i == rem)
    {
        count++;
    }


    if(i == rem && count >= 2)
        {
            printf("\n%d is present %d times", i, count);
        }
    }
}
return 0;
}

它返回正确的答案,但不是我需要的方式。感谢您的帮助!

最佳答案

此代码将为您提供每个数字的数量

#include <stdlib.h>
int main()
{
int num, div=1, rem,j,  i;
printf("Enter Number: ");
scanf("%d", &num);    //3002
div = num;
int count[10]={0,0,0,0,0,0,0,0,0,0};
while(div>0)
{

rem=div%10;
div=div/10;
printf("%d \n",rem);

for(i=0; i<=9; i++)
{

if(rem==i)
{
count[i]=count[i]+1;
}
}
}
for(j=0;j<=9;j++)
{
printf("%d",count[j]);}
return 0;
 }

如果输入数字 3002,它将输出 2011000000,表示 2 个 0、1 个二和 1 个三。

关于c - 如何查找数字0-9在整数中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38931218/

相关文章:

在visual studio中制作直接跳转

c - 如何从ARM中的32位端口的第15脚获取值?

c - ANSI C 警告 : assignment from incompatible pointer type

string - 在 bash 的字符串中“揭示”隐藏/控制 'codes'

c - 通过无效指针获取结构成员时如何更改编译器行为

arrays - ANSI C - 数组的较高元素

c++ - "~ "如何在 C 中找到补集?

c - 汇编和调用栈

c - 为什么在 C 中向后迭代数组比向前迭代快

c - Windows 上的 ANSI C 文件权限?