c++ - 在 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 字符串。
这是更好的代码版本
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++;
)
推荐阅读
- javascript - 如何用 html 标签替换字符?(丰富的文字)
- ios - 如何在 React Native 中获取带有 UITableViewCellStyleSubtitle 的原生 UITableView?
- java - 如何通过返回对象的反射来检索类类型?
- tabs - 如何使用 JFXBadge
- sql - SQL将两列合并为一
- anylogic - 如何在anylogic中获得车道上的汽车数量?
- hibernate - 如何直接从 jpql 查询(休眠)构造自定义对象列表
- google-chrome - Chrome 仅将某些图像显示为 webp
- excel - 迭代时如何计算目录中所有文件的总和?
- mongodb - MongoDB - 聚合找到没有。条目日期明智的