十進制浮點數轉二進制是計算機組成原理與嵌入式開發常見練習。本程序採用**遞歸**分別處理整數部分(除 2 取餘逆序)與小數部分(乘 2 取整順序),支援負數、可配置目標進制(預設二進制),代碼簡潔適合教學。
#include <stdio.h>
#include <stdlib.h>
#define BASE 2
#define EPS 1e-6 // 小數部分終止閾值
// 遞歸輸出整數部分:除基取餘,逆序列印
void printIntPart(int n) {
if (n > 0) {
printIntPart(n / BASE);
printf("%d", n % BASE);
}
}
// 遞歸輸出小數部分:乘基取整,順序列印
void printFracPart(double f) {
if (f > EPS) {
f *= BASE;
int digit = (int)f;
printf("%d", digit);
printFracPart(f - digit);
}
}
int main() {
double input;
printf("請輸入一個十進制小數: ");
if (scanf("%lf", &input) != 1) return 1;
// 處理負數
if (input < 0) {
printf("-");
input = -input;
}
int intPart = (int)input;
double fracPart = input - intPart;
printf("轉換為 %d 進制: ", BASE);
if (intPart == 0) printf("0");
else printIntPart(intPart);
if (fracPart > EPS) {
printf(".");
printFracPart(fracPart);
}
printf("\n");
system("pause"); // Windows 保持控制台
return 0;
}
請輸入一個十進制小數: 13.625 轉換為 2 進制: 1101.101 請輸入一個十進制小數: -7.1 轉換為 2 進制: -111.0001100110011...
13 / 2 = 6 ... 1 6 / 2 = 3 ... 0 3 / 2 = 1 ... 1 1 / 2 = 0 ... 1 (商為 0 結束) 讀餘數逆序:1101
0.625 × 2 = 1.25 → 整數 1,餘 0.25 0.25 × 2 = 0.5 → 整數 0,餘 0.5 0.5 × 2 = 1.0 → 整數 1,餘 0.0 (結束) 讀整數順序:101
void printIntPartIter(int n) {
char buf[64]; int top = 0;
if (n == 0) { putchar('0'); return; }
while (n) { buf[top++] = '0' + n % BASE; n /= BASE; }
while (top--) putchar(buf[top]);
}
void printFracPartIter(double f, int maxDigits) {
while (f > EPS && maxDigits--) {
f *= BASE;
int d = (int)f;
putchar('0' + d);
f -= d;
}
}