C++ 二进制数与十进制数相互转换程序

要理解本示例,您应该了解以下 C++ 编程 主题


示例 1:C++ 程序将二进制数转换为十进制数

// convert binary to decimal

#include <iostream>
#include <cmath>

using namespace std;

// function prototype
int convert(long long);

int main() {
  long long n;
  cout << "Enter a binary number: ";
  cin >> n;
  cout << n << " in binary = " << convert(n) << " in decimal";
  return 0;
}

// function definition
int convert(long long n) {
  int dec = 0, i = 0, rem;

  while (n!=0) {
    rem = n % 10;
    n /= 10;
    dec += rem * pow(2, i);
    ++i;
  }

  return dec;
}

输出

Enter a binary number: 1101
1101 in binary = 13 in decimal

在此程序中,我们包含了头文件 cmath 以在程序中执行数学运算。

我们要求用户输入一个二进制数,并将其传递给 convert() 函数将其转换为十进制。

假设 n = 1101。让我们看看 convert() 函数中的 while 循环是如何工作的。

n != 0 rem = n % 10 n /= 10 i dec += rem * pow(2, i)
1101 != 0 1101 % 10 = 1 1101 / 10 = 110 0 0 + 1 * pow (2, 0) = 1
110 != 0 110 % 10 = 0 110 / 10 = 11 1 1 + 0 * pow (2, 1) = 1
10 != 0 11 % 10 = 1 11 /10 = 1 2 1 + 1 * pow (2, 2) = 5
1 != 0 1 % 10 = 1 1 / 10 = 0 3 5 + 1 * pow (2, 3) = 13
0 != 0 - - - 循环终止

因此,二进制的 1101 是十进制的 13

现在,让我们看看如何将十进制数转换为二进制数。


示例 2:C++ 程序将十进制数转换为二进制数

// convert decimal to binary

#include <iostream>
#include <cmath>
using namespace std;

long long convert(int);

int main() {
  int n, bin;
  cout << "Enter a decimal number: ";
  cin >> n;
  bin = convert(n);
  cout << n << " in decimal = " << bin << " in binary" << endl ;
  return 0;
}

long long convert(int n) {
  long long bin = 0;
  int rem, i = 1;

  while (n!=0) {
    rem = n % 2;
    n /= 2;
    bin += rem * i;
    i *= 10;
  }

  return bin;
}

输出

Enter a decimal number: 13
13 in decimal = 1101 in binary

假设 n = 13。让我们看看 convert() 函数中的 while 循环是如何工作的。

n != 0 rem = n % 2 n /= 2 i bin += rem * i i * = 10
13 != 0 13 % 2 = 1 13 / 2 = 6 1 0 + 1 * 1 = 1 1 * 10 = 10
6 != 0 6 % 2 = 0 6 / 2 = 3 10 1 + 0 * 10 = 1 10 * 10 = 100
3 != 0 3 % 2 = 1 3 / 2 = 1 100 1 + 1 * 100 = 101 100 * 10 = 1000
1 != 0 1 % 2 = 1 1 / 2 = 0 1000 101 + 1 * 1000 = 1101 1000 * 10 = 10000
0 != 0 - - - 循环终止

因此,十进制的 13 是二进制的 1101


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战