刷题(1)16进制转换

描述

写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。

输入描述:

输入一个十六进制的数值字符串。注意:一个用例会同时有多组输入数据,请参考帖子https://www.nowcoder.com/discuss/276处理多组输入的问题。

输出描述:

输出该数值的十进制字符串。不同组的测试用例用\n隔开。

示例1

输入:

0xA
0xAA

复制输出:

10
170
#include<iostream>
#include<math.h>
using namespace std;
/*
atoi函数包含头文件stdlib.h,函数功能:将字符串转换为int类型,不会进行数据范围的检查,即超过int输出上下限,参数为char *类型,需要string.c_str
*/
/*
stoi函数功能:字符串转int(10进制数),会进行数据上下限的检查
stoi(strResult, 0, 16); strResult为需要转换得字符串,0表示起始位,16表示要将16进制转换成10进制
说明:
某些编译器会报stoi函数找不到头文件,实际包含在string中,需要设置编译环境GNUC++11或iso C++11
本人是在Dev-C++ GNU C++11环境下测试的
/*
pow()函数是数学函数包含在math.h或者cmath头文件中,pow(16,0);表示16的0次幂
0xAB = B * pow(16, 0) + A * pow(16, 1);
*/
int main()
{
    std::string strResult;
    while (cin>>strResult)
    {
        cout<<stoi(strResult, 0, 16)<<endl;
    }
}
int main1()
{
    std::string strInput;
    while(cin>>strInput)
    {
        int iBit = 0;
        int iResult = 0;
        for (int i = strInput.length() - 1; i > 1; --i)
        {
            if (strInput[i] >= '0' && strInput[i] <= '9')
            {
                iResult += (strInput[i] - '0') * pow(16, iBit++);
               
            }
            else if (strInput[i] >= 'A' && strInput[i] <= 'F')
            {
                iResult += (strInput[i] - 'A' + 10) * pow(16, iBit++);
                
            }
            
        }
        cout<<iResult<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值