c++ - 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
解决方案
您可以使用按位运算符来完成
或者
你的答案是——
#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;
}
推荐阅读
- android - Android Studio Spinner 如果按钮单击时发生事件
- flutter - 为什么收到 json 的颤振响应没有反序列化
- excel - 如何制定一个单元格以累积就地求和对应于另一个单元格值更新
- android-jetpack-compose - Jetpack 组成动态小吃店位置
- shopware - 如何添加自己的 ADMIN API 路由和控制器?
- javascript - React中数据变化时如何运行临时效果?
- python - 烧瓶如何用在 SelectField 中选择的信息填充输入字段
- node.js - 在 Nodejs 中使用 curl 下载文件
- javascript - 如果 Redis 宕机,节点 Redis 会一直调用错误函数
- php - 使用加载符号 PHP 创建 CSV 问题