【发布时间】:2020-10-27 09:01:57
【问题描述】:
我尝试构建一个函数,将存储在字符串中的二进制数计算为存储在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
我在这里做错了什么?
【问题讨论】:
-
可能不相关:您可以像使用
const char*一样使用std::string,因为它重载了下标运算符[]。它甚至更好,因为它有一个length()-function,您可以使用它来代替strlen。您可以完全删除array。 -
还有一点提示:
'1' != 1但'1' == 49
标签: c++ binary decimal calculation