在此示例中,您將學(xué)習(xí)通過創(chuàng)建用戶定義的函數(shù)將二進(jìn)制數(shù)與十進(jìn)制相互轉(zhuǎn)換。
要理解此示例,您應(yīng)該了解以下C語言編程主題:
#include <math.h> #include <stdio.h> int convert(long long n); int main() { long long n; printf("輸入二進(jìn)制數(shù): "); scanf("%lld", &n); printf("%lld(二進(jìn)制)= %d(十進(jìn)制)", n, convert(n)); return 0; } 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; }
輸出結(jié)果
輸入二進(jìn)制數(shù): 110110111 110110111(二進(jìn)制)= 439(十進(jìn)制)
#include <math.h> #include <stdio.h> long long convert(int n); int main() { int n; printf("輸入十進(jìn)制數(shù)字: "); scanf("%d", &n); printf("%d(十進(jìn)制)= %lld(二進(jìn)制)", n, convert(n)); return 0; } long long convert(int n) { long long bin = 0; int rem, i = 1, step = 1; while (n != 0) { rem = n % 2; printf("步驟 %d: %d/2, 余 = %d, 商 = %d\n", step++, n, rem, n / 2); n /= 2; bin += rem * i; i *= 10; } return bin; }
輸出結(jié)果
輸入十進(jìn)制數(shù)字: 29 步驟 1: 29/2, 余 = 1, 商 = 14 步驟 2: 14/2, 余 = 0, 商 = 7 步驟 3: 7/2, 余 = 1, 商 = 3 步驟 4: 3/2, 余 = 1, 商 = 1 步驟 5: 1/2, 余 = 1, 商 = 0 29(十進(jìn)制)= 11101(二進(jìn)制)