首页 > 解决方案 > 在 C++ 中将二进制数转换为十进制数

问题描述

我试图构建一个函数,将存储在字符串中的二进制数计算为存储在long long. 我在想我的代码应该可以工作,但事实并非如此。

在这个二进制数101110111的例子中,十进制数是375。但我的输出完全令人困惑。

这是我的代码:

#include <string>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <string.h>

int main() {
    std::string stringNumber = "101110111";

    const char *array = stringNumber.c_str();
    int subtrahend = 1;
    int potency = 0;
    long long result = 0;

    for(int i = 0; i < strlen(array); i++) {
        result += pow(array[strlen(array) - subtrahend] * 2, potency);
        subtrahend++;
        potency++;
        std::cout << result << std::endl;
    }
}

这是输出:

1
99
9703
894439
93131255
9132339223
894974720087
76039722530902
8583669948348758

我在这里做错了什么?

标签: c++binarydecimalcalculation

解决方案


您忘记将数字转换为整数。另外,您真的不需要使用 C 字符串。

这是更好的代码版本

int main() {
    std::string stringNumber = "101110111";

    int subtrahend = 1;
    int potency = 0;
    long long result = 0;

    for(int i = 0; i < stringNumber.size(); i++) {
        result += pow(2*(stringNumber[stringNumber.size() - subtrahend] - '0'), potency);
        subtrahend++;
        potency++;
        std::cout << result << std::endl;
    }
}

从字符串中减去'0'数字会将数字转换为整数。

现在为了额外的功劳写一个不使用的版本pow(提示:potency *= 2;而不是potency++;


推荐阅读