#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
int main()
{
int a;
float a1;
int b;
int i=0;
int c[1024]={0};
printf("请输入一个正整十进制数:");
while(1)
{
scanf("%f",&a1);
if((int)a1==a1)
{
if(a1>0)
{
break;
}
else
{
printf("again:");
}
}
else
{
printf("again:");
}
}
a=(int)a1;
while((a/2)!=0)
{
b=a%2;
c[i++]=b;
a=a/2;
}
c[i]=1;
printf("二进制数为:");
for(i;i>-1;i--)
{
printf("%d ",c[i]);
}
printf("\n");
return 0;
}
很明显当输入是0时,输出是错误的。修正版本以及十进制转二进制的算法。
std::string converHexToBin(int hexNumber)
{
std::string binStr;
if(hexNumber < 0){
return binStr;
}
if(hexNumber == 0){
binStr.push_back('0');
return binStr;
}
while(hexNumber > 0){
int number = hexNumber % 2;
binStr.insert(0, std::to_string(number));
hexNumber /= 2;
}
return binStr;
}