描述
写出一个程序,接受一个十六进制的数,输出该数值的十进制表示。
输入描述:
输入一个十六进制的数值字符串。注意:一个用例会同时有多组输入数据,请参考帖子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; }
刷题(1)16进制转换
最新推荐文章于 2023-09-26 13:52:05 发布