以下是一个将十六进制数转换为十进制数的C++代码:
该代码首先提示用户输入一个十六进制数,并将其存储在字符串变量hex
中。然后,使用循环,从右到左处理字符串中的每个字符,根据字符的值计算其对应的十进制值,并将其添加到decimal
变量中。最后,程序输出计算出的十进制值。如果输入的十六进制数包含无效字符,则程序将显示错误消息并退出。
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
int main() {
string hex;
cout << "Enter a hex number: ";
cin >> hex;
int decimal = 0;
int base = 1;
int len = hex.length();
for (int i = len - 1; i >= 0; i--) {
if (hex[i] >= '0' && hex[i] <= '9') {
decimal += (hex[i] - '0') * base;
base *= 16;
} else if (hex[i] >= 'A' && hex[i] <= 'F') {
decimal += (hex[i] - 'A' + 10) * base;
base *= 16;
} else if (hex[i] >= 'a' && hex[i] <= 'f') {
decimal += (hex[i] - 'a' + 10) * base;
base *= 16;
} else {
cout << "Invalid hex number." << endl;
return 0;
}
}
cout << "The decimal equivalent of " << hex << " is " << decimal << endl;
return 0;
}