在 C++ 中将小数转成二进制数
在本教程中,我们将讨论将小数转成二进制数的程序。
为此,我们将提供小数和小数 ‘k’。我们的任务是将给定小数转成其二进制等价数,直至给定小数精度 ‘k’ 位。
示例
#include<bits/stdc++.h> using namespace std; //converting decimal to binary number string convert_tobinary(double num, int k_prec) { string binary = ""; //getting the integer part int Integral = num; //getting the fractional part double fractional = num - Integral; //converting integer to binary while (Integral) { int rem = Integral % 2; binary.push_back(rem +'0'); Integral /= 2; } //reversing the string to get the //required binary number reverse(binary.begin(),binary.end()); binary.push_back('.'); //converting fraction to binary while (k_prec--) { 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 n = 4.47; int k = 3; cout << convert_tobinary(n, k) << "\n"; n = 6.986 , k = 5; cout << convert_tobinary(n, k); return 0; }
输出
100.011 110.11111
广告