第3章 编程问题 3.2节 4

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/young2415/article/details/72632495

  编写一个程序来实现两个最大为300位的大整数的加法。一种方法是将每个数看作是一个列表,这个列表的每个元素是这个数的一个数字块。例如,整数179,534,672,198可以被存储为block[0]=198,block[1]=672,block[2]=534,block[3]=179。然后将这个整数(列表)逐个元素的进行相加,在需要时从一个元素向下一个元素进位。

C++实现:

#include <iostream>
#include <climits>
using namespace std;

#define BLOCK 8   //数组中每个元素存储的数字的位数

void sum(const unsigned* const a, const unsigned* const b, unsigned *result);
void display(const unsigned* const array);

void main() {
    unsigned a[40] = { 95765432, 34532189, 99903999 };
    unsigned b[40] = { 34767891, 78653912, 88760033 };
    unsigned result[10] = { 0 };
    sum(a, b, result);
    display(result); //输出计算结果
    system("pause");
}

/*----------------------------------------
数组a里的数和数组b里的数相加,结果保存到
数组result中去。
数组a和数组b的最后一个元素是0,作为数组的结束标
志。初始时result中的元素应全部为0
const unsigned* const a:指针a指向的值不可改变,且指针a本身的值也不可改变
------------------------------------------*/
void sum(const unsigned* const a, const unsigned* const b, unsigned *result) {
    unsigned carry = 0;//保存进位
    int i = 0, j = 0, k = 0;
    while (a[i] && b[j]) {//当数组a和数组b的当前元素都不为0的时候,执行循环体
        unsigned temp = (a[i] + b[j]);  //临时变量存储a和b对应元素相加的和
        result[k] = carry + temp % (int)pow(10, BLOCK);
        carry = temp / (int)pow(10, BLOCK);
        i++;
        j++;
        k++;
    }
    result[k] = carry;
    while (a[i] != 0) {
        result[k] = result[k] + a[i];
        k++;
        i++;
    }
    while (b[j] != 0) {
        result[k] = result[k] + b[j];
        k++;
        j++;
    }
}

/*------------------------------------
从数组的最后一个正整数开始,依次向前输出数
组中元素的值
--------------------------------------*/
void display(const unsigned* const array) {
    int i = 0;
    while (array[i]) { i++; }
    i--;
    while (i >= 0) {
        cout << array[i--] << " ";
    }
}

程序中给出的两个数的运算结果是:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/young2415/article/details/72632495