Online Compiler C

#include <stdio.h> void print_digit_count(char number[]) { int cnt[10] = {0}; while (number > 0) { int d = number % 10; cnt[d]++; number = number / 10; } for (int i = 0; i < 10; i++) { if (cnt[i] > 0) { printf("%d %d\n", i, cnt[i]); } } }
这段代码试图统计一个数字字符串中每个数字出现的次数,但存在几个关键问题。

- 函数参数是字符数组 `char number[]`,但代码中却把它当作整数来使用,比如 `number % 10` 和 `number / 10`。字符数组和整数是不同的类型,不能直接进行算术运算。
- 循环条件 `number > 0` 对字符数组没有意义,因为数组名代表地址,不会自动变成数值。

- 你需要先理解如何从字符数组中逐个取出字符,并判断它是不是数字字符('0' 到 '9')。
- 字符 '0' 到 '9' 在计算机中是用 ASCII 码存储的,你可以通过减去 '0' 来得到对应的整数值。