#include<stdio.h>
#include<math.h>
int radix10(long int n);
int main()
{
long int n,dec; //定义2进制待转数和10进制转后数
printf("Input a binary number:\n");
scanf("%ld",&n);
dec=radix10(n);
printf("The number is %ld in decimal.\n",dec);
printf("The number is %o in octal.\n",dec);
printf("The number is %X in hexadecimal.\n",dec);
return 0;
}
int radix10(long int n) //转换为10进制
{
int decimalNumber = 0,i=0,remainder;
while(n!=0){
remainder = n%10; //取余数
n /=10; //剔除最后一位的数
decimalNumber += remainder*pow(2,i);
++i;
}
return decimalNumber;
}
codeblocks:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
在线编译(这个答案是正确的):