79 lines
2.5 KiB
C++
79 lines
2.5 KiB
C++
#include <iostream>
|
||
#include <string>
|
||
#include <algorithm>
|
||
#include <cmath>
|
||
using namespace std;
|
||
int convertToDecimal(const string& number, int base) {
|
||
int decimalValue = 0;
|
||
int length = number.length();
|
||
|
||
for (int i = 0; i < length; ++i) {
|
||
char digit = number[length - i - 1]; // Считываем цифры с конца
|
||
int value;
|
||
|
||
if (digit >= '0' && digit <= '9') {
|
||
value = digit - '0';
|
||
}
|
||
else if (digit >= 'A' && digit <= 'F') {
|
||
value = digit - 'A' + 10;
|
||
}
|
||
else if (digit >= 'a' && digit <= 'f') {
|
||
value = digit - 'a' + 10;
|
||
}
|
||
else {
|
||
throw invalid_argument("Недействительная цифра в числе");
|
||
}
|
||
|
||
if (value >= base) {
|
||
throw invalid_argument("Цифра неверна для сс (осуждаю)");
|
||
}
|
||
|
||
decimalValue += value * pow(base, i);
|
||
}
|
||
|
||
return decimalValue;
|
||
}
|
||
|
||
string convertFromDecimal(int number, int base) {
|
||
string result;
|
||
|
||
while (number > 0) {
|
||
int remainder = number % base;
|
||
if (remainder < 10) {
|
||
result += (remainder + '0'); // Добавляем цифры 0-9
|
||
}
|
||
else {
|
||
result += (remainder - 10 + 'A'); // Добавляем буквы A-F
|
||
}
|
||
number /= base;
|
||
}
|
||
|
||
reverse(result.begin(), result.end()); // Переворачиваем результат
|
||
return result.empty() ? "0" : result; // Если результат пустой, возвращаем "0"
|
||
}
|
||
|
||
int main() {
|
||
string inputNumber;
|
||
int oldBase, newBase;
|
||
setlocale(LC_ALL, "");
|
||
cout << "Введите число: ";
|
||
cin >> inputNumber;
|
||
cout << "Введите основание исходной системы счисления (2-16): ";
|
||
cin >> oldBase;
|
||
cout << "Введите основание новой системы счисления (2-16): ";
|
||
cin >> newBase;
|
||
|
||
try {
|
||
// Переводим число в десятичную систему
|
||
int decimalValue = convertToDecimal(inputNumber, oldBase);
|
||
// Переводим число из десятичной системы в новую систему счисления
|
||
string result = convertFromDecimal(decimalValue, newBase);
|
||
cout << "Результат: " << result << endl;
|
||
}
|
||
catch (const invalid_argument& e) {
|
||
cerr << "Ошибка: " << e.what() << endl;
|
||
}
|
||
|
||
return 0;
|
||
}
|