please answer it in C++
Expert Answer
- Comment
This is the code : read comments carefully i have mentioned each step in comments:
I used the method one : First discard the integral part and then doing operation with fractional part :
Code:#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define nline "\n"
#define mod (ll)(1e9+7)
// Function to convert decimal to binary upto
// k-precision after decimal point
string decimalToBinary(double num, int k_prec)
{
string binary = ""; // i used this string to store in a binary format
// Fetch the integral part of decimal number
int Integral = num;
// Fetch the fractional part decimal number
double fractional = num - Integral;// Conversion of fractional part to
// binary equivalent
while (k_prec--)
{
// Find next bit in fraction
fractional *= 2; // this will do multiplication
int fract_bit = fractional; // if fraction become 1.675 (assume) int actually take 1 here and discarded fraction.
if (fract_bit == 1) // if its equal one just add into a string one into it
{
fractional -= fract_bit; //remove those bit here
binary.push_back(1 + '0'); // update our string
}
else
binary.push_back(0 + '0');
}
return binary;
}
int main() {
double number;
cin>>number;
int k;
cin>>k;
number=number-(int)(number); // remove integral part only fraction part be there .
if(number<0){
cout<<"invalid";
}
else{
cout<<decimalToBinary(number,k)<<endl;
}
}Code:With less comments.
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define nline "\n"
#define mod (ll)(1e9+7)
// 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 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;
}
int main() {
double number;
cin>>number;
int k;
cin>>k;
number=number-(int)(number);
if(number<0){
cout<<"invalid";
}
else{
cout<<decimalToBinary(number,k)<<endl;
}
}
ليست هناك تعليقات:
إرسال تعليق