c++ - 十六进制到十进制转换器不起作用(c ++)
问题描述
因此,作为作业的一部分,我编写了一个将十六进制转换为十进制的程序。但我无法得到想要的结果。有人可以指出此代码中的错误吗?
#include<bits/stdc++.h>
#include<math.h>
using namespace std;
int hexaToDecimal(string n){
int ans = 0;
int power =1;
int s = n.size();
for(int i=s-1; i>=0; i--){
if(n[i] >= '0' && n[i] <= '9'){
ans = ans + power*(n[i]);
}
else if(n[i] >= 'A' && n[i] <= 'F'){
ans = ans + power*(n[i]-'A' + 10);
}
power = power * 16;
}
return ans;
}
int main(){
string n;
cin>>n;
cout<<hexaToDecimal(n)<<endl;
return 0;
}
解决方案
更简单的方法:
unsigned fromHex(const string &s) {
unsigned result = 0;
for (char c : s)
result = result << 4 | hexDigit(c);
return result;
}
unsigned hexDigit(char c) {
return c > ‘9’ ? c - ‘A’ + 10: c - ‘0’;
}
推荐阅读
- javascript - 发送日期 JavaScript -> Python -> MySQL 时出现问题:“unicode”对象没有属性“isoformat”
- windows - 我可以同时在多个服务器中调用相同的 RPC 函数吗?
- java-8 - 消费者附上try catch逻辑不起作用
- javascript - 如何设置谷歌图表纵轴增量?如何在网格栏上设置最大宽度?
- reactjs - 使用 React 从 Foursquare 获取场地描述
- c# - .NET 4.6 上的 ASP.NET Core - 如何使用 https
- azure - Azure 数据工厂管道基于参数运行
- adobe-illustrator - 无法写入文件,Illustrator 中的断言失败
- bash - 如何在命令行中传递分组参数
- sql - 当 Postgres 中的列可以为空时处理索引上的冲突