forked from randerson112358/C-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumToBinary.c
More file actions
52 lines (34 loc) · 1.01 KB
/
Copy pathNumToBinary.c
File metadata and controls
52 lines (34 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
Take any number in base 10 and convert it to binary
Ex: .625 to binary is .101
Ex2: 5 to binary is 101
Ex3: 5.625 to binary is 101.101
*/
#include<stdio.h>
double OriginalNum;
int toBinary(int decimalNo); //Converts an integer to binary
double DecToBin(double decNum); //Converts a fraction to binary
int main(void){
double num = 5.1;
int Int_num = (int)num;
double Float_num = num - (double)Int_num;
double answer = (double)(toBinary(Int_num) + DecToBin(Float_num));
OriginalNum = Float_num;
printf("%lf converted to binary is %lf \n", num, answer);
}
toBinary(int decimalNo){
//Base Case
if(decimalNo < 2)
return decimalNo;
//Recursive Case
return toBinary(decimalNo / 2) * 10 + decimalNo%2;
}
double DecToBin(double decNum){
double currentNum = decNum * 2.0;
double remainder = ((int)currentNum) % 2;
//Base Case
if(currentNum == 1 || currentNum == OriginalNum)
return remainder / 10;
//Recursive Case
return DecToBin( currentNum - remainder)/ 10 + remainder/10;
}