c - 需要用递归的方法来解决这个问题

标签 c

好吧,问题如下..我需要输入一个数字,程序需要打印该数字的位数< 5。数字的打印应该使用递归函数来完成。示例:“对于数字 8423871 应打印 4231 : 4”。这是我的没有递归的解决方案,有人可以帮我解决递归解决方案吗..

int main() 

{

    int n, pom, digit=0, a;
    printf("Enter a number: ");
    scanf("%d", &n);
    pom=n;
    while(pom > 0)
    {
        a = pom % 10;
        if(a < 5)
            digit++;
        pom=pom/10;
    }
    printf("%d : %d\n", n, digit);

    return 0;
}

最佳答案

#include <stdio.h>

int func_r(int n, int counter){
    int q = n / 10;
    int r = n % 10;
    if(n == 0) return counter;
    if(r < 5){
        counter = func_r(q, counter + 1);
        printf("%d", r);
    } else {
        counter = func_r(q, counter);
    }
    return counter;
}

int main(){
    int n, digit;
    printf("Enter a number: ");
    scanf("%d", &n);
    digit = func_r(n, 0);
    printf(" : %d\n", digit);

    return 0;
}

关于c - 需要用递归的方法来解决这个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20869471/

相关文章:

c - C 中的 qsort 是我的程序中意想不到的瓶颈

c - 从 char 到 const char 的转换无效

c - 在c中更新随机访问文件

c - 我在这个 C 程序中检查字符串是否是回文时做错了什么?

c - MIPS 中的 lw(也有点 C)

C语言: why do these two printf statements print different things

c - Eclipse C/C++ 头文件未找到

c - 如何使用嵌入式 C 启动 ARM Cortex 编程?

c - 如何选择何时打印字符数组中的特定字符

c - 编写时给出错误答案但复制时给出正确答案的程序