delphi - Number system convertion with Recursive function - Error in return value -


i have make program have convert numbers decimal system 1 (base 2 9), in first question.

but time have make using recursive function. came with:

function cambiarbase(n,b: integer): string; begin if n < b   cambiarbase := inttostr(n) else    cambiarbase := inttostr(n mod b) + cambiarbase(n div b, b); end; 

it takes 2 integer variables, 'n' being decimal number , 'b' being base, , returns string converted number. @ button procedure show number in tmemo

memo1.lines.add(cambiarbase(n,b));  

the problem have is: function way gives digits in reverse order (e.g. 301 in base 9 364, shown 463). if use reversestring function after if statement number shown in different order (in example, number 634).

but if apply reversestring function @ memo1.lines.add (outside of function) shows correct convertion.

what want know how can make return correct order of digits function itself.

the program compiles without errors.

again, reading.

leoam

you need reverse order of concatenation. instead of:

cambiarbase := inttostr(n mod b) + cambiarbase(n div b, b); 

you write

cambiarbase := cambiarbase(n div b, b) + inttostr(n mod b); 

if think should obvious concatenation should way round. in expression, inttostr(n mod b) term less significant term , appears on right.

for worth, think code reads better if use result rather function name. recursive function can hard visually distinguish between result variable , recursive call. i'd write this:

function cambiarbase(n, b: integer): string; begin   if n < b     // termination     result := inttostr(n)   else      // recursive step     result := cambiarbase(n div b, b) + inttostr(n mod b); end; 

let's work through simple example sake of illustration. let's 27 base 4 know equal 123 (16 + 2*4 + 3).

cambiarbase(27, 4) = cambiarbase(6, 4) + inttostr(3) 

next need evaluate

cambiarbase(6, 4) = cambiarbase(1, 4) + inttostr(2) 

and termination

cambiarbase(1, 4) = inttostr(1) 

plug , have

cambiarbase(27, 4) = inttostr(1) + inttostr(2) + inttostr(3) 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -