以下是使用基础的C语言数组算法实现计算书的全部页码分别用到多少次数字0,1,2,……,9的代码:

#include <stdio.h>

void countDigits(int n, int count[])
{
    for (int i = 0; i <= 9; i++) {
        count[i] = 0;
    }

    for (int i = 1; i <= n; i++) {
        int num = i;
        while (num > 0) {
            int digit = num % 10;
            count[digit]++;
            num /= 10;
        }
    }
}

int main()
{
    int n;
    printf("Enter the total number of pages: ");
    scanf("%d", &n);

    int count[10];
    countDigits(n, count);

    printf("Digits count:\n");
    for (int i = 0; i <= 9; i++) {
        printf("%d: %d\n", i, count[i]);
    }

    return 0;
}

这段代码中,countDigits函数用于计算书的全部页码分别用到多少次数字0,1,2,……,9。count数组存储每个数字的计数结果。

main函数中,首先从用户输入中获取总页码数n。然后,创建一个count数组,并调用countDigits函数计算页码中的数字计数。最后,使用循环打印每个数字的计数结果。

示例输出:

Enter the total number of pages: 100
Digits count:
0: 11
1: 21
2: 20
3: 20
4: 20
5: 20
6: 20
7: 20
8: 20
9: 20

这里的示例输出表示在1到100的页码中,数字0出现了11次,数字1出现了21次,数字2到9都出现了20次。

C语言数组算法实现书页码数字计数

原文地址: http://www.cveoy.top/t/topic/hvfv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录