Chuyển số thập phân (có phần nguyên và phần thập phân) sang nhị phân với độ chính xác k chữ số sau dấu phẩy.
Input: 4.47, k=3 -> 100.011 Input: 6.986, k=5 -> 110.11111
Giải pháp: Phần nguyên: chia 2 lấy dư đảo ngược. Phần thập phân: nhân 2 liên tiếp k lần, lấy phần nguyên.
Chương trình minh họa
#include <bits/stdc++.h>
using namespace std;
string convert_tobinary(double num, int k_prec){
string binary = "";
int Integral = (int)num;
double fractional = num - Integral;
while (Integral){
int rem = Integral % 2;
binary.push_back(rem + '0');
Integral /= 2;
}
reverse(binary.begin(), binary.end());
binary.push_back('.');
while (k_prec--){
fractional *= 2;
int fract_bit = (int)fractional;
if (fract_bit == 1){
fractional -= fract_bit;
binary.push_back('1');
} else binary.push_back('0');
}
return binary;
}
int main(){
double n = 4.47; int k = 3;
cout << convert_tobinary(n, k) << "\n";
n = 6.986; k = 5;
cout << convert_tobinary(n, k);
return 0;
}
Kết quả
100.011 110.11111