二进制转化为十进制c++ 代码
时间: 2023-11-16 21:00:58
浏览: 66
将二进制转化为十进制可以使用以下[代码](https://geek.csdn.net/educolumn/1572ef9b473b4e00f6b2bf6d428b7c27?spm=1055.2569.3001.10083):
```c++
#include <iostream>
#include <cmath>
using namespace std;
int main() {
[string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083) binary;
cout << "请输入一个二进制数:";
cin >> binary;
int decimal = 0;
for (int i = 0; i < binary.length(); i++) {
decimal += (binary[i] - '0') * pow(2, binary.length() - i - 1);
cout << "转化为十进制为:" << decimal << endl;
return 0;
该[代码](https://geek.csdn.net/educolumn/1572ef9b473b4e00f6b2bf6d428b7c27?spm=1055.2569.3001.10083)首先读入一个二进制数,然后使用循环和幂[[函数](https://geek.csdn.net/educolumn/2319d2a62911adc34b96ea572d8225a2?spm=1055.2569.3001.10083)](https://geek.csdn.net/educolumn/ba94496e6cfa8630df5d047358ad9719?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)将其转化为十进制数,并输出结果。
--相关问题--:
1. 如何将十进制转化为二进制?
2. 如何将十进制转化为八进制或十六进制?
相关问题
二进制转化为十进制c++代码
好的,以下是将二进制转化为十进制的C++代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int main() {
string binary;
cout << "请输入一个二进制数:";
cin >> binary;
int decimal = 0;
for (int i = 0; i < binary.length(); i++)
```