好吧,问题如下..我需要输入一个数字,程序需要打印该数字的位数< 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/