Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

แปลงทศนิยมเศษส่วนเป็นเลขฐานสองใน C++

ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมแปลงทศนิยมเศษส่วนเป็นเลขฐานสอง (binary)

สำหรับนี้ เราจะได้รับทศนิยมเศษส่วนและจำนวนเต็ม 'k' งานของเราคือแปลงทศนิยมเศษส่วนที่กำหนดให้เป็น binary equivalent จนถึง 'k' หลักความแม่นยำของทศนิยม

โปรแกรมตัวอย่าง

#include <bits/stdc++.h>
using namespace std;

// แปลงทศนิยมเป็น binary
string convert_tobinary(double num, int k_prec) {
    string binary = "";
    // ส่วนจำนวนเต็ม
    int Integral = num;
    // ส่วนทศนิยม
    double fractional = num - Integral;
    // แปลงจำนวนเต็มเป็น binary
    while (Integral) {
        int rem = Integral % 2;
        binary.push_back(rem + '0');
        Integral /= 2;
    }
    // กลับสตริงเพื่อได้ binary ที่ถูกต้อง
    reverse(binary.begin(), binary.end());
    binary.push_back('.');
    // แปลงทศนิยมเป็น 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