在C中的整数具体数字计数 [英] Specific digit count in an integer in C

查看:125
本文介绍了在C中的整数具体数字计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:如果用户输入的是11234517,并希望看到在此输入1的数,输出将是1的次数为3,我希望你明白我的意思。

For example: if user input is 11234517 and wants to see the number of 1's in this input, output will be "number of 1's is 3. i hope you understand what i mean.

我只能算一个整数位数。

i am only able to count number of digits in an integer.

#include <stdio.h>
int main()
{
    int n, count = 0;

    printf("Enter an integer number:");
    scanf("%d",&n);
    while (n != 0)
    {
        n/=10;
        count++;
    }
    printf("Digits in your number: %d",count);
    return 0;
}

也许阵列的解决方案。任何帮助将是AP preciated。谢谢!

maybe arrays are the solution. Any help would be appreciated. thank you!

推荐答案

所以,你已经发现,你可以转换 1234 123 通过使用(即去掉最低显著位)数/ 10

So, you've already found that you can convert 1234 to 123 (that is, remove the least significant digit) by using number / 10.

如果我们想要获得最显著的数字,我们可以使用若干%10 。对于 1234 ,这将具有的价值 4

If we wanted to acquire the least significant digit, we could use number % 10. For 1234, that would have the value of 4.

了解这一点,我们就可以修改你的code到考虑到这一点:

Understanding this, we can then modify your code to take this into account:

int main() {
    int n, count = 0;

    printf("Enter an integer number:");
    scanf("%d",&n);

    while (n != 0) {
        if (n % 10 == 1)
            count++;
        n /= 10;
    }

    printf("Number of 1s in your number: %d", count);
    return 0;
}

这篇关于在C中的整数具体数字计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆