Files
ARPZ-s1-pr3/task3.cpp
2024-11-16 10:00:23 +03:00

60 lines
1.8 KiB
C++
Raw 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.
// Задание 3
// В задании 2 была реализована идея ускорения суммирования двоичных
// чисел. Реализуйте сложение десятичных чисел с использованием
// подобного механизма ускорения.
#include <iostream>
int* addDecimal(int* A, int* B, int size) {
int* result = new int[size + 1](); // Результат может быть на 1 разряд больше
int carry = 0; // Перенос
for (int i = size - 1; i >= 0; i--) {
// Сложение с учетом переноса
int sum = A[i] + B[i] + carry; // Сложение
result[i + 1] = sum % 10; // Текущий разряд
carry = sum / 10; // Перенос
}
result[0] = carry; // Записываем перенос в старший разряд
return result;
}
int main() {
std::setlocale(LC_ALL, "ru");
int size;
std::cout << "Введите длину десятичных чисел: ";
std::cin >> size;
int* a = new int[size]();
int* b = new int[size]();
std::cout << "Введите первое десятичное число (цифры от 0 до 9): ";
for (int i = 0; i < size; i++) {
std::cin >> a[i];
}
std::cout << "Введите второе десятичное число (цифры от 0 до 9): ";
for (int i = 0; i < size; i++) {
std::cin >> b[i];
}
int* result = addDecimal(a, b, size);
std::cout << "Результат сложения: ";
for (int i = 0; i < size + 1; i++) {
std::cout << result[i] << " ";
}
std::cout << std::endl;
// Освобождаем память
delete[] a;
delete[] b;
delete[] result;
return 0;
}