基础练习 十六进制转十进制

一直提交不对

先改成了long long,(int表示有符号数为-2147483648到2147483647,FFFFFFFF超了(这里它作为无符号数,当然超了,有符号数就不会超)),还是不对,long也不对sizeof=4,和int一样也占四个字节,cout输出long long会出错应该是得格式化输出,直接用了

printf("%I64d",sum);不加I64不对

后来改了 sum+=(s[i]-48)*(int)(pow(16,s.length()-i-1));----> sum+=(s[i]-48)*(pow(16,s.length()-i-1));去掉了int强转就对了,原因是16的好多次幂会超了int的范围

#include <iostream>
using namespace std;
#include<math.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#include<stdio.h>
int main(int argc, char** argv) {
    
int sum=0;
    string s;
    cin>>s;
    int i=0;
    for(i=0;i<s.length();i++)
    {
        switch(s[i])
        {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            
            case '7':
            case '8':
            case '9':{
            sum+=(s[i]-48)*(pow(16,s.length()-i-1));
                break;
            }
            case 'A':
            case 'B':
            case 'C':
            case 'D':
            case 'E':
            case 'F':{
            sum+=(s[i]-55)*(pow(16,s.length()-i-1));
                break;
            }
        }
    }
printf("%I64d",sum);
    return 0;
}
原文地址:https://www.cnblogs.com/zhangshuyao/p/8010743.html