Decimal conversions to base numbers 2-16 (Binary through Hexadecimal)

前端 未结 6 1626
夕颜
夕颜 2021-01-16 15:03

Hey i\'m writing a program that converts decimal numbers into any base unit from binary to hexadecimal (2,3,4,....,15,16). This is what I have so far, running any number fro

6条回答
  •  不要未来只要你来
    2021-01-16 15:59

    The purpose of this program is to learn how to convert numbers to other bases, not just to try out printf when it gives you a shortcut. Why not try:

    if (y > 1 && y <= 16) {
         parsedNumber = convert(x, y);
    } else {
         reportIllegalBase(y);
    }
    

    with appropriate methods?

    Also, don't use x and y for variable names. You are writing this for understanding, not to play Code Golf.

    You should also try to make this a more general purpose program. Instead of printing everything as you calculate, construct a string (a char[]) and print that. So, the convert function I suggested you write should be declared as:

    char[] convert(const int number, const int base) {...}
    

    or

    void convert(int * const buffer, const int number, const int base) {...}
    

    By the way, what happens if x is negative? I'm not sure whether you do the right thing. You might want to get x from the user first, and then get y from the user. That way you can give the user a second chance if he types in 1 instead of 16:

    int getBase() {
        int base;
        while(true) {
            printf("Please type in the base: ");
            scanf("%d", &base);
            if (base > 1 && base <= 16) {
                return base;
            } else {
                printf("\nThe base must be between 2 and 16 inclusively.  You typed %d.\n",
                    base);
            }
         }
    }
    

    By the way, even though it isn't standard, there are reasons to use higher bases. A book I have titled Programming as if People Mattered by Nathaniel S. Borenstein (ISBN 0691037639) describes a situation where a college printed out randomly generated IDs on mailing labels. Unfortunately, sometimes the IDs looked like 2378gw48fUCk837 or he294ShiT4823, and recipients thought the school was cursing them.

    A committee convened to suggest words that should not appear in those IDs. A student intern came up with this idea to make the committee unnecessary: Just use base 31 and leave out the vowels. That is, use 0123456789bcdfghjklmnpqrstvwxyz as the base-31 digits. This cut down on the work, made a lot of programming unnecessary, and put people out of a job.

提交回复
热议问题