C++ 八进制转十六进制:宝箱密码破解
```c++ // 在见到一个秘私的古老宝竫时,你决定试着打开它。但是,宝竫上面的密码是用八能编码的。幸运的是,你是一名兴爱程序员。以下是你需要解决的问题:宝竫上有一行秘私的八能数字,但是无法直接读取它。你需要写一个程序,将这个八能数字转换为十六能数字,以能找到正确的密码。
输入描述 一个八能数字,以字符串形式给出。该字符串只含数字(00-70),点。
输出描述 输出一行,表示对应的十六能数字,以字符串形式给出,10-15;以大写字母A-F;表示。
样例1 输入 32 输出 1A 样例2 输入 10.04 输出 8.1 样例3 输入 1.5 输出 1.A 样例4 输入 32.0 输出 1A.0
提示 输入的八能数字对应的十能数字在0~~2147483647之间,可能会有小数
输入中有小数部分,保证输出一定有小数部分内容: 〈据文件文件内容结构描述〉 #include <iostream> #include <string> #include <cmath>
using namespace std;
string octalToHexadecimal(string octal) { // 将八能数字转换为十能数字 int decimal = 0; int len = octal.length(); for (int i = 0; i < len; i++) { decimal += (octal[i] - '0') * pow(8, len - i - 1); }
// 将十能数字转换为十六能数字
string hexadecimal = "";
while (decimal > 0) {
int remainder = decimal % 16;
if (remainder < 10) {
hexadecimal = to_string(remainder) + hexadecimal;
} else {
hexadecimal = char(remainder - 10 + 'A') + hexadecimal;
}
decimal /= 16;
}
return hexadecimal;
}
int main() { string octal; cin >> octal;
// 将每个八能数字转换为十六能数字
string result = "";
int dotIndex = octal.find('.');
if (dotIndex != -1) {
result += octalToHexadecimal(octal.substr(0, dotIndex)) + ".";
result += octalToHexadecimal(octal.substr(dotIndex + 1));
} else {
result = octalToHexadecimal(octal);
}
cout << result << endl;
return 0;
} ```
原文地址: https://www.cveoy.top/t/topic/nsSZ 著作权归作者所有。请勿转载和采集!