Files
dz4/z-9.cpp
2024-11-16 00:05:34 +03:00

85 lines
2.7 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#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 <= 'Z') {
value = digit - 'A' + 10;
}
else if (digit >= 'a' && digit <= 'z') {
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-Z
}
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-36): ";
cin >> oldBase;
cout << "Введите основание новой системы счисления (2-36): ";
cin >> newBase;
if (oldBase < 2 || oldBase > 36 || newBase < 2 || newBase > 36) {
cerr << "Основания должны быть в диапазоне от 2 до 36." << endl;
return 1;
}
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;
}