0

I'm writing a method that turns a decimal number into any radix (2-36) and prints the appropriate chars to the screen. The decimalToSymbol() method works correctly. The problem I'm having is in the while loop I assign ans[i] to a char and when I try to print it immediately after it is 0. I have looked online and found this is an OK way to assign the char but am not sure what is going wrong.

void writeRadixB(int decimalNumber, int radixB)
{
        char ans[80] = ""; 
        int i = 0;
        while(decimalNumber!= 0){ 
                printf("decNum: %d div by rB: %d equals %d\n", decimalNumber, radixB, decimalN
                printf("decNum: %d mod by rB: %d equals %d or char %c\n", decimalNumber, radix
                printf("i: %d\n", i); 
                decimalNumber = decimalNumber/radixB;
                ans[i] = decimalToSymbol(decimalNumber%radixB);
                printf("ans[%d] is %c\n", i, ans[i]);
                i++;
        }   
        printf("(%s) radix %d", ans, radixB);
}
4
  • Can you give an example of the values you're passing in? Also, shouldn't you be doing the modulus before you divide away the last digit each time? Commented Feb 1, 2012 at 20:52
  • I agree with FatalError and also want to note, that your digits will be ordered backwards in the string you create. Commented Feb 1, 2012 at 20:53
  • 1
    How do you know that the decimalToSymbol method works correctly? Also make sure to null terminate your string. `ans[i]='\0';1 before you print. Commented Feb 1, 2012 at 20:54
  • besides you should initialize char ans[80] = {0}; you should also check if (radixB != 0) return;. I'm not quite sure what purpose negative values would have here either. You should also add the (complete) output of your program to enhance the question... Commented Feb 1, 2012 at 21:07

2 Answers 2

1

You shouldn't change decimalNumber until AFTER you've extracted your digit. That, and your result is backwards.

Sign up to request clarification or add additional context in comments.

Comments

0

You should put the line ans[i] = decimalToSymbol(decimalNumber%radixB); before the line decimalNumber = decimalNumber/radixB;, (to not lose a digit). also, you probably want to reverse the string before printing it.

1 Comment

This was my problem, thank you. Just have to print the string backwards now

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.