2025-03-04 学习记录--C/C++-PTA 习题5-5 使用函数统计指定数字的个数

合抱之木,生于毫末;九层之台,起于累土;千里之行,始于足下。💪🏻

一、题目描述 ⭐️


二、代码(C语言)⭐️

c 复制代码
#include <stdio.h>

int CountDigit( int number, int digit );

int main()
{
    int number, digit;

    scanf("%d %d", &number, &digit);
    printf("Number of digit %d in %d: %d\n", digit, number, CountDigit(number, digit));

    return 0;
}

/* 你的代码将被嵌在这里 */
int CountDigit(int number, int digit) {
    // 特殊情况:如果 number 是 0 且 digit 也是 0,直接返回 1
    if (number == 0 && digit == 0) {
        return 1;
    }

    int count = 0; // 初始化计数器,用于记录 digit 在 number 中出现的次数

    // 如果 number 是负数,将其转换为正数
    if (number < 0) {
        number *= (-1);
    }

    // 遍历 number 的每一位
    while (number != 0) {
        // 取出 number 的最后一位
        int lastDigit = number % 10;

        // 如果最后一位等于 digit,计数器加 1
        if (lastDigit == digit) {
            count++;
        }

        // 去掉 number 的最后一位
        number /= 10;
    }

    // 返回 digit 在 number 中出现的次数
    return count;
}


相关推荐
●VON21 小时前
React Native for OpenHarmony:2048 小游戏的开发与跨平台适配实践
javascript·学习·react native·react.js·von
ZH154558913121 小时前
Flutter for OpenHarmony Python学习助手实战:自动化脚本开发的实现
python·学习·flutter
xcLeigh1 天前
Python入门:Python3 requests模块全面学习教程
开发语言·python·学习·模块·python3·requests
xcLeigh1 天前
Python入门:Python3 statistics模块全面学习教程
开发语言·python·学习·模块·python3·statistics
GHL2842710901 天前
分析式AI学习
人工智能·学习·ai编程
lpruoyu1 天前
【Android第一行代码学习笔记】Android架构_四大组件_权限_持久化_通知_异步_服务
android·笔记·学习
野犬寒鸦1 天前
从零起步学习并发编程 || 第六章:ReentrantLock与synchronized 的辨析及运用
java·服务器·数据库·后端·学习·算法
wdfk_prog1 天前
[Linux]学习笔记系列 -- [drivers][mmc][mmc_sdio]
linux·笔记·学习
果果燕1 天前
今日学习笔记:双向链表、循环链表、栈
笔记·学习·链表
觉醒大王1 天前
AI写的青基中了
人工智能·笔记·深度学习·学习·职场和发展·学习方法