Repository navigation
Expand file tree
/
Copy pathdec.cpp
More file actions
69 lines (54 loc) · 1.36 KB
/
Copy pathdec.cpp
File metadata and controls
69 lines (54 loc) · 1.36 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// C++ program to convert fractional decimal
// to binary number
#include<bits/stdc++.h>
using namespace std;
// Function to convert decimal to binary upto
// k-precision after decimal point
string decimalToBinary(double num, int k_prec)
{
string binary = "";
// Fetch the integral part of decimal number
int Integral = num;
// Fetch the fractional part decimal number
double fractional = num - Integral;
// Conversion of integral part to
// binary equivalent
while (Integral)
{
int rem = Integral % 2;
// Append 0 in binary
binary.push_back(rem +'0');
Integral /= 2;
}
// Reverse string to get original binary
// equivalent
reverse(binary.begin(),binary.end());
// Append point before conversion of
// fractional part
binary.push_back('.');
// Conversion of fractional part to
// binary equivalent
while (k_prec--)
{
// Find next bit in fraction
fractional *= 2;
int fract_bit = fractional;
if (fract_bit == 1)
{
fractional -= fract_bit;
binary.push_back(1 + '0');
}
else
binary.push_back(0 + '0');
}
return binary;
}
// Driver code
int main()
{
double n;
cin>>n;
int k = 6;
cout << decimalToBinary(n, k) << "\n";
return 0;
}