简体   繁体   English

C中整数形式的特定位数

[英]Specific digit count in an integer in C

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. 例如:如果用户输入为11234517,并且想要在此输入中看到1的数量,则输出将为“ 1的数量为3。我希望您理解我的意思。

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;
}

maybe arrays are the solution. 也许数组是解决方案。 Any help would be appreciated. 任何帮助,将不胜感激。 thank you! 谢谢!

You don't need array. 您不需要数组。 Try something like this: 尝试这样的事情:

int countDigits(int number, int digitToCount)
{
  // Store how many times given number occured
  int counter = 0;

  while(number != 0)
  {
   int tempDigit = number % 10;
   if(tempDigit == digitToCount)
     counter++;
   number = number/10;
  }

 return counter;
}

So, you've already found that you can convert 1234 to 123 (that is, remove the least significant digit) by using number / 10 . 因此,您已经发现可以使用number / 101234转换为123 (即,删除最低有效数字)。

If we wanted to acquire the least significant digit, we could use number % 10 . 如果要获取最低有效位,可以使用number % 10 For 1234 , that would have the value of 4 . 对于1234 ,其值为4

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;
}

You may want to use convert your int to a string like this : 您可能要使用将您的int转换为这样的字符串

char str[100];
sprintf(str, "%d", n);

Then, you can just iterate on str in order to find the occurrences of your digit. 然后,您可以仅在str上进行迭代以查找数字的出现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM