47 lines
1.1 KiB
C
47 lines
1.1 KiB
C
/*-----------------------------------------------------------------------
|
|
【程序设计】
|
|
-------------------------------------------------------------------------
|
|
题目:编写函数实现用除二取余的方法,把任意一个十进制正数的二进制序列输出
|
|
(不考虑溢出)
|
|
程序输入输出如下所示
|
|
Enter a decimal number: 2
|
|
The binary representation is: 10
|
|
-------------------------------------------------------------------------
|
|
------------------------------------------------------------------------*/
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
void decimalToBinary(int decimal)
|
|
{
|
|
int remainder;
|
|
int len = 0;
|
|
char binary[32];
|
|
int i;
|
|
if (decimal == 0)
|
|
{
|
|
printf("0");
|
|
return;
|
|
}
|
|
/**********Program**********/
|
|
for(i=0;decimal>0;i++,decimal/=2){
|
|
binary[i] = decimal%2+48;
|
|
}
|
|
binary[i] = '\0';
|
|
i--;
|
|
for(;i>len;i--){
|
|
remainder = binary[len];
|
|
binary[len] = binary[i];
|
|
binary[i] = remainder;
|
|
len++;
|
|
}
|
|
/********** End **********/
|
|
printf("%s\n", binary);
|
|
}
|
|
int main()
|
|
{
|
|
int number;
|
|
printf("【Enter a decimal number: 】");
|
|
scanf("%d", &number);
|
|
printf("【The binary representation is: 】");
|
|
decimalToBinary(number);
|
|
}
|