69,368
社区成员
发帖
与我相关
我的任务
分享
char result[ DIGIT ];
......
return result;
result是stack上的内在,返回之后没了,自然乱码,另外,你的那个代码也没考虑最后也进位的情况,比如9999+1,显然结果是10000,你没考虑最后的一次进位
全部改正之后代码基本如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
# define DIGIT 100
//返回result记得free
char * AddOperation( char * a1, char * a2 )
{
int next = 0;
int i = 0;
int count1 = strlen( a1 );
int count2 = strlen( a2 );
char* result = new char[DIGIT];
while( *a1 != '\0' )
a1 ++;
while( *a2 != '\0' )
a2 ++;
a1 --;
a2 --;
while( ( count1 > 0 ) && ( count2 > 0 ) )
{
if( ( * a1 - 48 ) + ( * a2 - 48 ) + next > 9 )
{
result[ i ] = (char)( ( * a1 - 48 ) + ( * a2 - 48 ) + next - 10 ) + '0';
next = 1;
}
else
{
result[ i ] = (char)( ( * a1 - 48 ) + ( * a2 - 48 ) + next ) + '0';
next = 0;
}
count1 --;
a1 --;
count2 --;
a2 --;
i ++;
}
while( count1 > 0 )
{
if( ( * a1 - 48 ) + next > 9 )
{
result[ i ] = (char)( ( * a1 - 48 ) + next - 10 ) + '0';
next = 1;
}
else
{
result[ i ] = (char)( ( * a1 - 48 ) + next ) + '0';
next = 0;
}
count1 --;
a1 --;
i ++;
}
while( count2 > 0 )
{
if( ( * a2 - 48 ) + next > 9 )
{
result[ i ] = (char)( ( * a2 - 48 ) + next - 10 ) + '0';
next = 1;
}
else
{
result[ i ] = (char)( ( * a2 - 48 ) + next ) + '0';
next = 0;
}
count2 --;
a2 --;
i ++;
}
if(next){
result[i++]='1';
}
result[ i ] = '\0';
return result;
}
int main( void )
{
char adder1[ DIGIT ];
char adder2[ DIGIT ];
puts( "Please input adder1" );
scanf("%s",adder1);
puts( "Please input adder2" );
scanf("%s", adder2);
printf( "The result of %s + %s is %s\n", adder1, adder2, AddOperation(adder1, adder2));
return 0;
}
BigInt& BigInt::operator+(BigInt & b);
#include <stdio.h>
#include <string.h>
#define MAXLEN 1000
char a1[MAXLEN];
char a2[MAXLEN];
static int v1[MAXLEN];
static int v2[MAXLEN];
static int v3[MAXLEN];
int i,j,n,L,z;
void main(void) {
scanf("%d",&n);
for (j=0;j<n;j++) {
scanf("%s%s",a1,a2);
L=strlen(a1);
for (i=0;i<L;i++) v1[i]=a1[L-1-i]-'0';
L=strlen(a2);
for (i=0;i<L;i++) v2[i]=a2[L-1-i]-'0';
for (i=0;i<MAXLEN;i++) v3[i]=v1[i]+v2[i];
for (i=0;i<MAXLEN;i++) {
if (v3[i]>=10) {
v3[i+1]+=v3[i]/10;
v3[i]=v3[i]%10;
}
}
printf("Case %d:\n", j+1);
printf("%s + %s = ", a1, a2);
z=0;
for (i=MAXLEN-1;i>=0;i--) {
if (z==0) {
if (v3[i]!=0) {
printf("%d",v3[i]);
z=1;
}
} else {
printf("%d",v3[i]);
}
}
if (z==0) printf("0");
printf("\n");
}
}
//Sample Input
//3
//0 0
//1 2
//112233445566778899 998877665544332211
//
//Sample Output
//Case 1:
//0 + 0 = 0
//Case 2:
//1 + 2 = 3
//Case 3:
//112233445566778899 + 998877665544332211 = 1111111111111111110