输入一个整数a和一个个位数的整数b,请输出整数b在整数a中出现的次数。题目保证整数b为0-9之间的个位整数。
时间: 2024-10-13 22:07:05 浏览: 166
这是一个基础的字符串操作问题,在C语言中可以转换成查找字符的问题。我们可以将整数a转化为字符串,然后遍历这个字符串,对于每个字符,检查它是否等于b,如果相等则计数器加一。以下是简单的步骤:
1. 使用`itoa`函数将整数a转换成字符串。
2. 初始化一个计数器变量count为0。
3. 遍历字符串中的每一个字符,如果是数字b,则count加1。
4. 循环结束后,返回count作为结果。
下面是一个简单的C语言实现示例:
```c
#include <stdio.h>
#include <string.h>
int count_char(int a, int b) {
char str[100];
sprintf(str, "%d", a);
int count = 0;
for (int i = 0; i < strlen(str); i++) {
if (str[i] == '0' + b) { // '+' operator converts ASCII digit to integer
count++;
}
}
return count;
}
int main() {
int a, b;
scanf("%d %d", &a, &b);
printf("Number of occurrences of %d in %d is %d\n", b, a, count_char(a, b));
return 0;
}
```
阅读全文
相关推荐















