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

โปรแกรม C++ แปลงเลขฐานสอง (Binary) ↔ ฐานสิบ (Decimal) ทั้งสองทาง


Binary ใช้ฐาน 2, Decimal ใช้ฐาน 10

ตัวอย่าง:

DecimalBinary
1001010
700111
2511001
1610000

ตัวอย่างโค้ด (2 ฟังก์ชัน)

#include <iostream>
using namespace std;

void DecimalToBinary(int n) {
    int binaryNumber[100], num = n;
    int i = 0;
    while (n > 0) {
        binaryNumber[i] = n % 2;
        n = n / 2;
        i++;
    }
    cout << "Binary form of " << num << " is ";
    for (int j = i - 1; j >= 0; j--)
        cout << binaryNumber[j];
    cout << endl;
}

int BinaryToDecimal(int n) {
    int decimalNumber = 0;
    int base = 1;
    int temp = n;
    while (temp) {
        int lastDigit = temp % 10;
        temp = temp / 10;
        decimalNumber += lastDigit * base;
        base = base * 2;
    }
    cout << "Decimal form of " << n << " is " << decimalNumber << endl;
}

int main() {
    DecimalToBinary(23);
    BinaryToDecimal(10101);
    return 0;
}

ผลลัพธ์

Binary form of 23 is 10111
Decimal form of 10101 is 21

DecimalToBinary

while n>0: เก็บ n%2 ใน array, n/=2, i++ แล้วพิมพ์ย้อนกลับ (j=i-1 ถึง 0)

while (n > 0) {
    binaryNumber[i] = n % 2;
    n = n / 2;
    i++;
}
for (int j = i - 1; j >= 0; j--)
    cout << binaryNumber[j];

BinaryToDecimal

while temp≠0: lastDigit = temp%10, decimalNumber += lastDigit×base, base×=2, temp/=10

while (temp) {
    int lastDigit = temp % 10;
    temp = temp / 10;
    decimalNumber += lastDigit * base;
    base = base * 2;
}

main()

DecimalToBinary(23);
BinaryToDecimal(10101);