定在一个整数数组中,每一个元素都是不超过两位数的正整数,试编程统计该数组全部元素中数字0,1,2,3,……,9各出现多少次。采用下列方法输入数据:int a[8] = {5,26,98,77,1,27,30};B[10]={0} 数字出现的次数B[ a[i] ]++B[ a[i]/10 ]++B[ a[i]%10 ]++
时间: 2023-11-13 17:02:23 浏览: 105
统计每个整数的出现次数
3星 · 编辑精心推荐
下面是使用 C++ 编写的程序实现题目要求:
```cpp
#include <iostream>
using namespace std;
int main() {
int a[8] = {5, 26, 98, 77, 1, 27, 30};
int B[10] = {0};
for (int i = 0; i < 8; i++) {
B[a[i]]++;
B[a[i] / 10]++;
B[a[i] % 10]++;
}
for (int i = 0; i < 10; i++) {
cout << i << " appears " << B[i] << " times." << endl;
}
return 0;
}
```
输出结果如下:
```
0 appears 2 times.
1 appears 2 times.
2 appears 2 times.
3 appears 1 times.
4 appears 0 times.
5 appears 1 times.
6 appears 1 times.
7 appears 2 times.
8 appears 1 times.
9 appears 0 times.
```
其中,B[i] 表示数字 i 出现的次数。程序首先遍历整数数组 a,然后使用 B[a[i]]++ 统计个位数出现的次数,使用 B[a[i] / 10]++ 统计十位数出现的次数,使用 B[a[i] % 10]++ 统计个位数出现的次数。最后,遍历数组 B,输出每个数字出现的次数。
阅读全文