用c语言计算在区间 1 到 n 的所有整数中,数字x (0 ≤ x ≤ 9)共出现了多少次?
时间: 2024-05-15 12:01:17 浏览: 29
可以使用循环遍历区间内的每个整数,然后统计数字x在该整数中出现的次数。
具体实现可以将整数转化为字符串,然后遍历字符串中的每个字符,判断是否等于数字x,若相等则累加计数器。代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int count(int n, int x) {
int i, j, cnt = 0;
char str[20];
for (i = 1; i <= n; i++) {
sprintf(str, "%d", i); // 将整数转化为字符串
for (j = 0; j < strlen(str); j++) {
if (str[j] - '0' == x) { // 判断字符串中的数字是否等于x
cnt++;
}
}
}
return cnt;
}
int main() {
int n, x;
printf("请输入区间上限n和数字x:");
scanf("%d%d", &n, &x);
printf("数字%d在区间1到%d中共出现了%d次。\n", x, n, count(n, x));
return 0;
}
```
注意,此处使用了`sprintf()`函数将整数转化为字符串,需要包含`<stdio.h>`头文件。
相关问题
用C语言试计算在区间1到n的所有整数中,数字x(0 ≤ x ≤ 9)共出现了多少次?
以下是用C语言实现在区间1到n的所有整数中,数字x共出现了多少次的代码:
```c
#include <stdio.h>
int count(int n, int x);
int main()
{
int n, x, res;
printf("请输入区间n的值:");
scanf("%d", &n);
printf("请输入数字x的值:");
scanf("%d", &x);
res = count(n, x);
printf("数字%d在区间1到%d的所有整数中共出现了%d次\n", x, n, res);
return 0;
}
int count(int n, int x)
{
int i, digit, cnt = 0;
for (i = 1; i <= n; i++)
{
int num = i;
while (num)
{
digit = num % 10;
if (digit == x)
cnt++;
num /= 10;
}
}
return cnt;
}
```
该算法的时间复杂度为O(nlogn),其中n为区间1到n的整数个数。可以通过循环遍历每个数字的每一位,判断该位是否为数字x来实现计数。
试计算在区间1到n的所有整数中,数字x(0≤x≤9)共出现了多少次? 输入描述: 输入共1行,包含2个整数n、x,之间用一个空格隔开。 输出描述: 输出共1行,包含一个整数,表示x出现的次数。用c语言表示
#include <stdio.h>
int main()
{
int n, x, count = 0;
scanf("%d %d", &n, &x);
for (int i = 1; i <= n; i++)
{
int temp = i;
while (temp)
{
if (temp % 10 == x) count++;
temp /= 10;
}
}
printf("%d\n", count);
return 0;
}
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)