分析:
代码:
- #include "stdio.h"
- /* 函数声明 */
- void GetBibary(long int x);
- void GetOctal(long int x);
- void GetHexadecimal(long int x);
- /* 主函数 */
- int main(void)
- {
- long int x;
- printf("我会帮您把大于等于零的十进制数转换成二进制、八进制、十六进制数。\n");
- printf("请输入您想要转换的十进制数:");
- scanf("%ld",&x);
- if(x<0)
- {
- printf("请输入大于等于零的十进制数!\n");
- }
- else
- {
- GetBibary(x);
- GetOctal(x);
- GetHexadecimal(x);
- }
- return 0;
- }
- /* 求二进制的函数 */
- void GetBibary(long int x)
- {
- long int X,quotient,remainder;
- long int i=0,j,binary[32];
- X=x;
- if(x>=0&&x<2)
- {
- printf("%ld的二进制数是%ld.\n",x,x);
- }
- else
- {
- do
- {
- quotient=x/2;
- remainder=x%2;
- binary[i]=remainder;
- x=quotient;
- i++;
- }while(x>=2);
- binary[i]=quotient;
- printf("%ld的二进制数为:",X);
- for(j=i;j>=0;j--)
- {
- printf("%ld",binary[j]);
- }
- printf("\n");
- }
- }
- /* 求八进制的函数 */
- void GetOctal(long int x)
- {
- long int X,quotient,remainder;
- long int i=0,j,octal[16];
- X=x;
- if(x>=0&&x<8)
- {
- printf("%ld的八进制数是%ld.\n",X,x);
- }
- else
- {
- do
- {
- quotient=x/8;
- remainder=x%8;
- octal[i]=remainder;
- x=quotient;
- i++;
- }while(x>=8);
- octal[i]=quotient;
- printf("%ld的八进制数为:",X);
- for(j=i;j>=0;j--)
- {
- printf("%ld",octal[j]);
- }
- printf("\n");
- }
- }
- /* 求十六进制的函数 */
- void GetHexadecimal(long int x)
- {
- long int X,quotient,remainder;
- long int i=0,j,hexadecimal[8];
- char change[6]={'F','E','D','C','B','A'};
- X=x;
- if(x>=0&&x<10)
- {
- printf("%ld的十六进制数是%ld.\n",X,x);
- }
- else if(x>=10&&x<16)
- {
- x=16-(x+1);
- printf("%ld的十六进制数是%c.\n",X,change[x]);
- }
- else
- {
- do
- {
- quotient=x/16;
- remainder=x%16;
- hexadecimal[i]=remainder;
- x=quotient;
- i++;
- }while(x>=16);
- hexadecimal[i]=quotient;
- printf("%ld的十六进制数为:",X);
- for(j=i;j>=0;j--)
- {
- if(hexadecimal[j]>=0&&hexadecimal[j]<10)
- {
- printf("%ld",hexadecimal[j]);
- }
- else
- {
- hexadecimal[j]=16-(hexadecimal[j]+1);
- printf("%c",change[(hexadecimal[j])]);
- }
- }
- printf("\n");
- }
- }
编译结果:
点石成金 写于 2012/08/10/01:27