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

前端 未结 6 1624
夕颜
夕颜 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

    Since x is not modified in this loop, z is always calculated the same value, and the loop never exits:

       while(z != 0){
       z = (x/y);
       c = (x%y);
       printf("%d\n", z);
       }
    

    To convert a number to a difference base, what you usually do is repeatedly divide the number by the base, and the remainders give you the digits. This will print out the digits from last to first:

       while(x != 0){
          c = (x%y); /* remainder of x when divided by y */
          x = (x/y); /* x divided by y */
          printf("%d\n", c);
       }
    

提交回复
热议问题