CCF NOI1089 高精度运算
问题链接:CCF NOI1089 高精度运算。
时间限制: 
1000 ms  空间限制: 262144 KB
题目描述
  输入N对位数不超过1000的正整数,求它们的和。
  (编程使用strunc创建一个bigNum类型,并对’+’号运算符重载)
输入
  第1行:一个正整数N,1≤N≤100;
  下面有N行,每行2个整数:a和b,位数都不超过1000。
输出
一个正整数:和。样例输入
1
12345  213
样例输出
12558
数据范围限制
  1≤N≤100
提示
 
问题分析
这是一个加法计算问题,但是给的数位数多,虽然说不超过1000位,那就是有可能好几百位,超出了所有整数类型能够表示的范围。
大数计算一种是构建一个大数类进行计算,另外一种是直接计算。
人们使用阿拉伯数字,据说是印度人发明的。需要注意的一点是,阿拉伯数字的高位在左边,阅读上是从左到右,而计算上人们则是从低位算起。
  大数可以放在数组中,为了计算上的方便,应该把低位放在下标小的地方,高位放在下标大的地方。
 读入的数可以放在字符数组或字符串变量中,高位在左低位在右。
  (略)
要点详解
- 使用宏定义可以使得代码可阅读性增强。
- 加法计算需要考虑进位,实际上每一位的加法是三个数相加。
 
参考链接:(略)。
100分通过的C语言程序:
#include <stdio.h>
#include <string.h>
#define BASE 10
#define N 1000
char a[N+1], b[N+1], ans[N+1];
int main(void)
{
    int n, lens, lent, carry, i, j;
    scanf("%d", &n);
    while(n--) {
        memset(ans, 0, sizeof(ans));
        scanf("%s", a);
        scanf("%s", b);
        lens = strlen(a);
        lent = strlen(b);
        for(i=lens-1,j=0; i>=0; i--,j++)
            ans[j] = a[i] - '0';
        carry = 0;
        for(i=lent-1,j=0; i>=0; i--,j++) {
            ans[j] += carry + b[i] - '0';
            carry = ans[j] / BASE;
            ans[j] %= BASE;
        }
        while(carry > 0) {
            ans[lent] += carry;
            carry = ans[lent] / BASE;
            ans[lent] %= BASE;
            lent++;
        }
        if(lent > lens)
            lens = lent;
        for(i=lens-1; i>=0; i--)
            printf("%c", '0' + ans[i]);
        printf("\n");
    }
    return 0;
}100分通过的C++语言程序:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
#define BASE 10
#define N 1000
char ans[N+1];
int main()
{
    int n, lens, lent, carry, i, j;
    string a, b;
    cin >> n;
    while(n--) {
        cin >> a >> b;
        memset(ans, 0, sizeof(ans));
        lens = a.length();
        lent = b.length();
        for(i=lens-1,j=0; i>=0; i--,j++)
            ans[j] = a[i] - '0';
        carry = 0;
        for(i=lent-1,j=0; i>=0; i--,j++) {
            ans[j] += carry + b[i] - '0';
            carry = ans[j] / BASE;
            ans[j] %= BASE;
        }
        while(carry > 0) {
            ans[lent] += carry;
            carry = ans[lent] / BASE;
            ans[lent] %= BASE;
            lent++;
        }
        if(lent > lens)
            lens = lent;
        for(i=lens-1; i>=0; i--)
            printf("%c", '0' + ans[i]);
        printf("\n");
    }
    return 0;
}
 
                    
                 
                
            
         
 浙公网安备 33010602011771号
浙公网安备 33010602011771号