【发布时间】:2020-09-12 11:45:19
【问题描述】:
我正在尝试使用 C++ 程序将十六进制值转换为十进制值。就是想不出一个有效的代码。
这是我想出的最好的东西:
int main () {
string link;
string hex_code;
int dec_code;
int i;
int n = 6;
int num;
int hex;
cout << "Insert 1 of the HEX characters at a time:";
for (i = 0; i < n; i++) {
cin >> hex_code;
}
for (i = 0; i < n; i++) {
if (hex_code == "A") {
hex_code = 10;
}
else if (hex_code == "B") {
hex_code = 11;
}
else if (hex_code == "C") {
hex_code = 12;
}
else if (hex_code == "D") {
hex_code = 13;
}
else if (hex_code == "E") {
hex_code = 14;
}
else if (hex_code == "F") {
hex_code = 15;
}
else {
hex_code = hex_code;
}
num = hex * pow (16, i);
}
for (i = 0; i < n; i++) {
dec_code = dec_code + num;
}
cout << dec_code;
return 0;
}
欢迎任何帮助/反馈/意见。
编辑:感谢您的所有帮助。在这里找到了我尝试创建但失败的代码:https://stackoverflow.com/a/27334556/13615474
【问题讨论】:
-
dec_code = dec_code + num应该在上面的 for 循环中 -
当
hex_code是std::string时,hex_code = 10毫无意义。应该是hex = 10;,六个地方有同样的问题。