• Post Reply Bookmark Topic Watch Topic
  • New Topic

recursion  RSS feed

 
aaron koh
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
H, i am currently learning recursion, and i have a query.

I have a program that receives user input, and outputs the decimal input into binary form.

In my recursive function, i have a if else loop to check if operation is completed. The problem i face is this.



The final return, when input finally hits zero is concatenating 0 to whatever i have this far. e.g. Decimal 10 should give 1010, but because of the "return 0", instead of getting
1010+0, i am getting 10100.
I can solve the problem by creating a variable sum,and passing along, but i am just curious why the final return 0 is giving me not a +0,but a concatenate 0.

Thanks in advance for the help rendered.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.

I don't quite understand what the calculation does, but I would start by converting everything from "int" to "double". Casting double results to int -as the code is currently doing- is bound to result in numerical inaccuracies otherwise. (Of course, using double introduces its own inaccuracies, but for small numbers that should be fine).
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think the problem is that it's concatenating - integers won't work like that. It might be clearer if you told us what the input was, but I'd be suspicious about that ++weight on line 11. Do you realise that the calculated value you print out on line 10 is not the same as the calculated value added to your result on line 11, because weight is incremented between the calculations? That would make a factor of 10 difference, which is what you're seeing.

My guess is that weight + 1 would do what you need, rather than ++weight.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!