C程序练习:二进制和十进制相互转换.
// convert binary to decimal
#include <stdio.h>
#include <math.h>
// function prototype
int convert(long long);
int main() {
long long n;
printf("Enter a binary number: ");
scanf("%lld", &n);
printf("%lld in binary = %d in decimal", n, convert(n));
return 0;
}
// function definition
int convert(long long n) {
int dec = 0, i = 0, rem;
while (n!=0) {
rem = n % 10;
n /= 10;
dec += rem * pow(2, i);
++i;
}
return dec;
}
结果:
|
1 2 |
Enter a binary number: 1101 1101 in binary = 13 in decimal |
除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!