Monday 15 February 2010

c++ - Recursion Binary to Decimal - completely stuck -



c++ - Recursion Binary to Decimal - completely stuck -

i using c++ write programme uses recursion convert user input binary number decimal. i've played code hours

(earlier initialized i i = binary.length();)

void bin2dec(string binary, int i) { double decnum=0; if (i >= 0) { if (binary[i] = 0) { decnum = (decnum + 0); } else { decnum = (decnum + pow(2, (i-1))); } bin2dec(binary, i-1); } cout << decnum; }

that recursion function. unfortunately, stuck. programme runs gives me wrong values. example, when plug in 1 binary, expect 1 decimal in return. .5 number. calculation wrong or using recursion incorrectly?

thank you!

upon receiving suggestions, made next changes. however, programme still returns wrong value.

void bin2dec(string binary, int i) { double decnum=0; if (i >= 0) { if (binary[i] == 1) { decnum = (decnum + pow(2, i)); } else if (binary[i] == 0) { decnum = (decnum + 0); } bin2dec(binary, - 1); cout << decnum; } }

assuming using little endian, should utilize pow(2, i). i-1, going have 1 in position 0 in array, means evaluate pow(2, -1), 0.5.

consider working illustration (https://ideone.com/pwvagp):

int bintodec(string binary, unsigned int = 0) { int tot = 0; if (i < binary.length()) { if (binary[i] == '1') tot = pow(2, i); else if (!binary[i] == '0') throw "string not formatted in binary"; homecoming tot + bintodec(binary, ++i); } homecoming tot; }

note it's possible start @ end of string , work backwards, prefer starting @ 0 since think simpler. total additions, easiest thing homecoming phone call of function, did @ end of if(i < binary.length() block. 1 time have nail base of operations case (in case i == binary.length()), homecoming 0, added total number doesn't alter it. 1 time base of operations case has returned, others begin returning portion of sum 1 above them, keeps getting added until reaches bottom of phone call stack, original calling function.

if not want homecoming answer, alter function signature void bintodec(int& tot, string binary, unsigned int = 0) , maintain adding value tot rather returning it, requires caller gives int modify.

c++ recursion

No comments:

Post a Comment