C语言 - 初学者学习被调函数 经典例题

输入一个正整数repeat (0<repeat<10),做repeat次下列运算:
读入1 个整数,统计并输出该数中2的个数。
要求定义并调用函数countdigit(number,digit),它的功能是统计整数number中数字digit
的个数。例如,countdigit(10090,0)的返回值是3。
例:括号内是说明
输入:
3 (repeat=3) 
-21902 
2 
345543 
输出:
count=2 (-21902中有2个2) 
count=1 (有1个2) 
count=0 (345543中没有2) 

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

int countdigit(int number, int digit)
{
	int count = 0;

	while(number != 0)
	{
		if( (number % 10) == digit || (number % 10) == -digit)
		{
			count++;
		}
		number = number / 10;
	}
	return count;
}

int main(void) 
{
	int repeat, i;
	int number;
	int digit;

	scanf("%d", &repeat);

	for(i=0; i<repeat; i++)
	{
		scanf("%d %d", &number, &digit);
		printf("count = %d\n", countdigit(number, digit) );
	}

	printf("\n");
	system("pause");
	return 0;
}

/*
-------------在VC++6.0中显示效果-------------
3
-21902 2
count = 2
2 2
count = 1
345543 2
count = 0

请按任意键继续. . .
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值