算法思路:
十进制转二进制的主要思路就是除2取余
#include <stdio.h>
long long convertDecimalToBinary(int n){
long long binarynumber;
int remainder;//余数
int weight=1;//权位
while(n!=0){
remainder = n%2;
n/=2;
binarynumber+=remainder*weight; //以二进制显示原来的十进制就是按位相加
weight*=10; //个位、十位、百位 以次递进
}
return binarynumber;
}
int main(void){
int n;
scanf("%d",&n);
printf("->十进制%d转二进制 %11d",n,convertDecimalToBinary(n));
return n;
}
写法二:
#include <stdio.h>
int main(){
int b[32] = {0},x,k,r,i;
printf("输入十进制数:\n");
scanf("%d",&x);
printf("\n");
k=-1;
do{
r=x%2;
b[++k] =r;
x/=2;
}
while(x>0);
printf("转换后的二进制:\n");
for(i=k;i>=0;i--){
printf("%d",b[i]);
}
printf("\n");
return 0;
}