Exercise 5-5 Use functions to count the number of specified numbers (15 point(s))

This question requires the realization of a simple function that counts the number of specified numbers in an integer.

Function interface definition:

int CountDigit( int number, int digit );

Where number is an integer not exceeding a long integer, and digit is an integer in the interval [0, 9]. The function CountDigit should return the number of occurrences of digit in number.

Sample referee test procedure:

#include <stdio.h>

int CountDigit( int number, int digit );

int main()
{
    
    
    int number, digit;

    scanf("%d %d", &number, &digit);
    printf("Number of digit %d in %d: %d\n", digit, number, CountDigit(number, digit));

    return 0;
}

/* 你的代码将被嵌在这里 */

Input sample:

21252 2

Sample output:

Number of digit 2 in -21252: 3

answer:

int CountDigit( int number, int digit )
{
    
    
	int cnt=0; //统计digit数字在number出现的次数
	if(number<0) number=-number; //如果number是负数 就变成正数
//	if(number==0) cnt=1; //do while循环可以少写这一条,while需要写这一条(因为number等于0时不会进入while循环,而do while是无条件进入在判断)
	do
	{
    
     //(0%10==0 所以cnt计数器会加一然后退出循环)
		if(digit==(number%10)) cnt++; //如果取模(取最后一位数)等于我们要查找的数,计数器加一
		number/=10; //每次循环到底部整除10把后一位去除掉
	}while(number);
	return cnt; //返回cnt给 CountDigit
}

Guess you like

Origin blog.csdn.net/qq_44715943/article/details/114584004