• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

recursion

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic