/*
編寫一個遞歸函數,求一個整數的2進制形式
輸入8
輸出 1000
輸入15
輸出 1111
void calc(int n);
calc(8);
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define N 20
void calc(int n);
int main(int argc, const char * argv[])
{
//提示用戶輸入十進制數
int n;
printf("請輸入一個十進制數:");
scanf("%d",&n);
//轉化爲二進制數
calc(n);
return 0;
}
void calc(int n)
{
int *a; //用來存放轉化的二進制數
int m = 0; //轉化的二進制位數
while (pow(2, m) < n) {
m++;
}
a = (int*)malloc(sizeof(int)*(m));
for (int i = 0; i < m; i ++)
{
a[i] = ((int)(n/pow(2, m-i-1)))%2;
}
for (int i = 0; i <= m - 1; i ++)
{
printf("%d",a[i]);
}
free(a);
}