由于整型数据的长度有限,在处理大数问题是要用到字符串,利用数组的长度来存储数据,并进行转换相加,下面以题目为例,进行说明;
Description
One of the first users of BIT's new supercomputer was Chip Diller. He extended his exploration of powers of 3 to go from 0 to 333 and he explored taking various sums of those numbers.
``This supercomputer is great,'' remarked Chip. ``I only wish Timothy were here to see these results.'' (Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky apartments on Third Street.)
Input
The input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger. Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no VeryLongInteger will be negative).
The final input line will contain a single zero on a line by itself.
Output
Your program should output the sum of the VeryLongIntegers given in the input.
Sample Input
123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890
0
Sample Output
370370367037037036703703703670
题意解析:输入多组大数求和,当输入为0时输出相加的和
思路要点:<1>利用字符串数组来存储大数 <2>声明第三个数组来存储相加之和 <3>注意输入循环和输出结果条件<4>考虑进位问题,如果相加和大于或等于10时向下一位进位
<5>注意相加开始的顺序,是从最后一位加起,即数组从后往前加
代码解释:
#include <stdio.h>
#include <string.h>
void add(char str1[], char str2[]) //声明相加函数
{
int a[1001], b[1001]; //声明两个整型数组存储字符串转换后的值
int len1,len2,i,j,c,m,temp,leap;
memset(a,0,sizeof(a)); //a,b两个数组置为0
memset(b,0,sizeof(b));
len1=strlen(str1); //求出相加的两个字符串的长度
len2=strlen(str2);
c=0;
for(i=len1-1;i>=0;i--) //把数组S1的转换数值存储到a数组
a[c++]=str1[i]-'0';
c=0;
for(i=len2-1;i>=0;i--) //把数组S2的转换数值存储到b数组
b[c++]=str2[i]-'0';
m=len1>len2 ? len1:len2; //找到S1,S2长度最长的一个,以便循环
leap=0; //设置进位变量,置为0
for(i=0;i<m;i++) //循环相加
{
temp=a[i]+b[i]+leap; //数组a的值加数组b的值
a[i]=temp%10; //求余并赋值给a数组
leap=temp/10; //求出进位的值
}
if(leap) //如果有进位把进位值放入a数组
{
a[i]=temp;
m++; //同时把存放结果的数组长度+1
}
for(i=0,j=m-1;j>=0;j--,i++) //由于最后要输出的字符串,所以再次把整型数转换字符型
str1[i]=a[j]+'0';
}
int main()
{
char s1[1001], s2[1001];
scanf("%s",s1);
while(scanf("%s",s2)!=EOF) //根据题意进行输入的控制
{
if(s2[0]=='0') //判断输入为0时输出多个大数相加的和
{
add(s1,s2);
printf("%s\n",s1);
memset(s1,0,sizeof(s1)); //输出后将s1数组的值置为0,不影响下一组数据的相加
}
else //不符合条件,进行相加然后继续输入
{
add(s1,s2);
}
}
return 0;
}