c - Recursion or extracting a variable -
void base_aux(unsigned int n, unsigned int base, unsigned int x) { zero_int(32 - x); if (n > (base - 1)) { base_aux(n / base, base, ++x); printf("%u", n % base); } else { printf("%u", n); } } void binary_int(unsigned int n) { base_aux(n, 2, 0); }
i'm making converter decimal whatever base. have use recursion , need print leading zeros. zeros print without recursing. call in actual function, don't know how incremented x this. please help.
zero_int helper function print many zeroes needed.
i.e @ moment when attempt convert 1288 decimal 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010100001000.
what 00000000000000000000010100001000.
i see because each recursive call repeatedly places leading zeroes, creates many, not sure how fix this.
considering base 2 (binary):
the trouble lies in place calling zero_int function. need ensure called once , correct value of x.
modifying code below should work:
void base_aux(unsigned int n, unsigned int base, unsigned int x) { if (n > (base - 1)) { base_aux(n / base, base, ++x); printf("%u", n % base); } else { ++x; zero_int(32 - x); printf("%u", n); } }
Comments
Post a Comment