C++中可以使用以下算法來實現進制轉換:
#include <iostream>
#include <string>
std::string decToBase(int num, int base) {
std::string result = "";
while (num > 0) {
int rem = num % base;
result = (char)(rem < 10 ? rem + '0' : rem + 'A' - 10) + result;
num /= base;
}
return result;
}
int main() {
int num = 123;
int base = 16;
std::string result = decToBase(num, base);
std::cout << result << std::endl;
return 0;
}
#include <iostream>
#include <string>
int baseToDec(const std::string& num, int base) {
int result = 0;
int power = 1;
for (int i = num.length() - 1; i >= 0; i--) {
int digit = (num[i] >= '0' && num[i] <= '9') ? (num[i] - '0') : (num[i] - 'A' + 10);
result += digit * power;
power *= base;
}
return result;
}
int main() {
std::string num = "7B";
int base = 16;
int result = baseToDec(num, base);
std::cout << result << std::endl;
return 0;
}
以上示例分別實現了十進制轉其他進制和其他進制轉十進制的算法,你可以根據實際需求,選擇合適的算法來進行進制轉換。