#include <iostream>

using namespace std;

void countDigits(int n) {
    int count[3] = {0}; // 初始化计数数组,分别用于统计数字1、2、3的次数
    
    while (n > 0) {
        int digit = n % 10; // 取出最低位的数字
        if (digit == 1) {
            count[0]++;
        } else if (digit == 2) {
            count[1]++;
        } else if (digit == 3) {
            count[2]++;
        }
        n /= 10; // 去掉最低位的数字
    }
    
    // 输出统计结果
    for (int i = 0; i < 3; i++) {
        cout << count[i] << " ";
    }
}

int main() {
    int n;
    cin >> n; // 输入整数n
    countDigits(n); // 统计各位上出现数字1、2、3的次数
    return 0;
}

解析: 首先,我们定义一个长度为3的数组count,用于统计数字1、2、3的出现次数。然后,我们通过不断地取出最低位的数字,判断该数字是否为1、2、3,然后对应地增加计数数组中的对应位置的值。最后,我们通过循环遍历计数数组,将各个数字出现的次数输出。

本关任务:编写函数函数功能是:统计整数n的各位上出现数字1、2、3的次数。要求输入输出均在主函数中完成。c++测试输入:123114350预期输出:3 1 2测试输入:1221114445533预期输出:4 2 2

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

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