#include <iostream>

// 统计整数n的各位上出现数字1、2、3的次数
void countDigits(int n) {
    int count1 = 0, count2 = 0, count3 = 0;
    while (n != 0) {
        int digit = n % 10; // 取出最低位的数字
        if (digit == 1) {
            count1++;
        } else if (digit == 2) {
            count2++;
        } else if (digit == 3) {
            count3++;
        }
        n /= 10; // 去掉最低位的数字
    }
    std::cout << "数字1出现的次数:" << count1 << std::endl;
    std::cout << "数字2出现的次数:" << count2 << std::endl;
    std::cout << "数字3出现的次数:" << count3 << std::endl;
}

int main() {
    int n;
    std::cout << "请输入整数n:";
    std::cin >> n;
    countDigits(n);
    return 0;
}

使用示例:

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

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

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