简体   繁体   English

使用递归显示数字的所有数字时无法打印数字的最后一位?

[英]Can't print last digit of a number while displaying all digits of a number using recursion?

I was trying to print digits of a number using recursion.我试图使用递归打印数字的数字。 The function I defined returns all the digits but I fail to print the last digit.我定义的 function 返回所有数字,但我无法打印最后一个数字。 Can any one point out what's wrong in the code?任何人都可以指出代码中有什么问题吗? Is there any other logic which is better than this with recursion?有没有比递归更好的其他逻辑?

 public static int printIndividualDigits(int num){
        if((num/10) != 0){
           System.out.print(printIndividualDigits(num/10)+ ",");
        }
         if(num != 0){
           return num%10;
        }else{
             return 0;
         }
    }

That's because you return the last character, but you print all the others.那是因为您返回最后一个字符,但打印所有其他字符。

In your recursive calls, you don't append the reminder to some globally available variable (which would be preferable way in your example), hence you don't build the answer to be printed;在您的递归调用中,您不会 append 提醒一些全局可用变量(在您的示例中这将是更可取的方式),因此您不会构建要打印的答案; rather you just print the remainders, per each recursive call, and then (important) return either num%10 or 0 .相反,您只需打印每个递归调用的余数,然后(重要)返回num%100

So, your first stack frame (which is initial method call, first entrance into the recursive method) returns , instead of printing.因此,您的第一个堆栈帧(这是初始方法调用,第一次进入递归方法)返回,而不是打印。

For instance, if you will take number 3435 , your last recursive call ends up to be:例如,如果您将使用号码3435 ,您的最后一个递归调用最终会是:

System.out.print(printIndividualDigits(34/10)+ ",");

which enters printIndividualDigits with argument 3 passed into "num" parameter, and then method prints 3%10 => 3 .它输入printIndividualDigits ,参数 3 传递给“num”参数,然后方法打印3%10 => 3

Now, when your recursive calls pop off the stack frame - that is your recursion goes back to the first recursive frame (that is a first recursive call), variable num is 3435, * there is no more recursive calls , and code execution passes System.out#print method call, to the if checks, after which, it returns either 0 , or the latest reminder, instead of printing it.现在,当您的递归调用从堆栈帧中弹出时——即您的递归返回到第一个递归帧(即第一次递归调用),变量num为 3435,*不再有递归调用,并且代码执行通过System.out#print方法调用,到if检查,之后,它返回0或最新的提醒,而不是打印它。

So, in the first stack frame, your return 3435%10 , which is 5 , gets just returned and not printed.因此,在第一个堆栈帧中,您的return 3435%10 (即5 )只是被返回而不被打印。

change int to double try it将 int 更改为 double 尝试

`
 public static double printIndividualDigits(double num){
        if((num/10) != 0){
           System.out.print(printIndividualDigits(num/10)+ ",");
        }
         if(num != 0){
           return num%10;
        }else{
             return 0;
         }
    }

`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM