You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
int toDecimal(const std::string& num, int base) {
int decimalValue = 0;
for (char digit : num) {
decimalValue *= base;
decimalValue += (isdigit(digit) ? digit - '0' : digit - 'A' + 10);
}
return decimalValue;
}
std::string fromDecimal(int decimalValue, int base) {
if (decimalValue == 0) return "0";
std::string result;
while (decimalValue > 0) {
int remainder = decimalValue % base;
result += (remainder < 10 ? '0' + remainder : 'A' + (remainder - 10));
decimalValue /= base;
}
std::reverse(result.begin(), result.end());
return result;
}
std::string convertBase(const std::string& num, int fromBase, int toBase) {
return fromDecimal(toDecimal(num, fromBase), toBase);
}
int main() {
std::string number;
int fromBase, toBase;
std::cout << "输入数字:";
std::cin >> number;
std::cout << "输入源进制2-16";
std::cin >> fromBase;
std::cout << "输入目标进制2-16";
std::cin >> toBase;
std::string convertedNumber = convertBase(number, fromBase, toBase);
std::cout << "转换后的数字是:" << convertedNumber << std::endl;
return 0;
}