Добавить z-9.cpp
This commit is contained in:
73
z-9.cpp
Normal file
73
z-9.cpp
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cmath>
|
||||||
|
|
||||||
|
int convertToDecimal(const std::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 std::invalid_argument("Invalid digit in the number.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value >= base) {
|
||||||
|
throw std::invalid_argument("Digit is not valid for the base.");
|
||||||
|
}
|
||||||
|
|
||||||
|
decimalValue += value * std::pow(base, i);
|
||||||
|
}
|
||||||
|
|
||||||
|
return decimalValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string convertFromDecimal(int number, int base) {
|
||||||
|
std::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;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::reverse(result.begin(), result.end()); // Переворачиваем результат
|
||||||
|
return result.empty() ? "0" : result; // Если результат пустой, возвращаем "0"
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
std::string inputNumber;
|
||||||
|
int oldBase, newBase;
|
||||||
|
|
||||||
|
std::cout << "Введите число: ";
|
||||||
|
std::cin >> inputNumber;
|
||||||
|
std::cout << "Введите основание исходной системы счисления (2-16): ";
|
||||||
|
std::cin >> oldBase;
|
||||||
|
std::cout << "Введите основание новой системы счисления (2-16): ";
|
||||||
|
std::cin >> newBase;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Переводим число в десятичную систему
|
||||||
|
int decimalValue = convertToDecimal(inputNumber, oldBase);
|
||||||
|
// Переводим число из десятичной системы в новую систему счисления
|
||||||
|
std::string result = convertFromDecimal(decimalValue, newBase);
|
||||||
|
std::cout << "Результат: " << result << std::endl;
|
||||||
|
} catch (const std::invalid_argument& e) {
|
||||||
|
std::cerr << "Ошибка: " << e.what() << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user