首页 > 解决方案 > c++ 中的 Potency-function 丢弃了令人困惑的结果

问题描述

我试图编写一个能够将二进制数转换为十进制数的函数。但不幸的是,最后需要添加的效力计算结果非常混乱。我在这里做错了什么?

代码:

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

int main() {
    std::string label = "10110";
    int subtrahend = 1;
    int potency = 0;
    int result = 0;
    int positionResult;

    for(int i = 0; i < label.length(); i++) {

        positionResult= pow(label[label.length() - subtrahend] * 2, potency);
        std::cout << positionResult<< std::endl;

        result += positionResult;
        subtrahend++;
        potency++;
    }
    std::cout << result << std::endl;
}

输出:

1
98
9604
884736
92236816
93131255

标签: c++binarydecimalpow

解决方案


您可以使用按位运算符来完成

或者

你的答案是——

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

int main() {
std::string label = "10110";
int subtrahend = 1;
int result = 0;
int positionResult;

for(int i = 0; i < label.length(); i++) {

    positionResult= pow(2,label.length() - subtrahend)*(label[i]-'0');
    std::cout << positionResult<< std::endl;

    result += positionResult;
    subtrahend++;
}
std::cout << result << std::endl;
}

推荐阅读