大数相加

来源:互联网 发布:java能调用api 编辑:程序博客网 时间:2024/06/01 10:30

大数相加

程序模拟竖式计算进行超大数相加:


/** * 大数相加 */#include<stdio.h>#include<stdlib.h>#include "string.h"#include "iostream"using namespace std;/* 函数声明 start */void reversal(char num[]);int getLength(char num[]);/* 函数声明 end *//** * 数组逆置 * @param num 数组 */void reversal(char a[]) {    int c = getLength(a);    int low = 0;    int high = c - 1;    for (int i = 0; i < c / 2; i++) {        if (low < high) {            int temp = a[c - i - 1];            a[c - i - 1] = a[i];            a[i] = temp;        }    }}/** * 求数组实际长度 * @param num  数组 * @return  数组实际长度 */int getLength(char num[]) {    int len = 0;    while (num[len] != '\0') {        len++;    }    return len;}/** * 计算结果 * @param num1 参数1 * @param num2 参数2 * @return 结果 */void getResult(char num1[], char num2[], char res[]) {    int length1 = getLength(num1);    int length2 = getLength(num2);    int temp = 0, i = 0;    reversal(num1);    reversal(num2);    for (int i = 0; i < length1 && i < length2; ++i) {        temp = (num1[i] - '0') + (num2[i] - '0') + temp;        res[i] = (temp % 10) + '0';        temp = temp / 10;    }    if (length1 < length2) {        for (i = length1; i < length2; i++) {            temp = (num2[i] - '0') + temp;            res[i] = temp % 10 + '0';            temp = temp / 10;        }    } else {        for (i = length2; i < length1; i++) {            temp = (num1[i] - '0') + temp;            res[i] = temp % 10 + '0';            temp = temp / 10;        }    }    if (temp != 0) {        res[i] = temp + '0';        res[i + 1] = '\0';    } else {        res[i] = '\0';    }    reversal(num1);    reversal(num2);//    cout << res << endl;}int main() {    char num1[1001], num2[1001], sum[1002];    cout << "请输入加数1:";    cin >> num1;    cout << "请输入加数2:";    cin >> num2;    getResult(num1, num2, sum);    reversal(sum);    cout << num1 << " + " << num2 << " = " << sum << endl;    return 0;}
原创粉丝点击