ADD file via upload

main
fdzcxy212206257 1 month ago
parent 3f6eea1539
commit f66adb7a64

@ -0,0 +1,47 @@
#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;
}
Loading…
Cancel
Save