输入被减数和减数,两个数为不超过200位的整数.,每行1个,输出差.
输入:
5324345634734328432
632345667456834
输出:
5323713289066871598
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#define N 1001
using namespace std ;
int main ( )
{
int a [ N ] , b [ N ] , c [ N ] , i ;
char n [ N ] , n1 [ N ] , n2 [ N ] ;
memset ( a , 0 , sizeof ( a ) ) ;
memset ( b , 0 , sizeof ( b ) ) ;
memset ( c , 0 , sizeof ( c ) ) ;
gets ( n1 ) ;
gets ( n2 ) ;
int lena = strlen ( n1 ) , lenb = strlen ( n2 ) ;
if ( lena < lenb || ( lena == lenb && strcmp ( n1 , n2 ) < 0 ) )
//strcmp()为字符串比较函数,当n1=n2时,返回0,
//n1>n2时,返回正整数;n1<n2时返回负整数
//比完大小后,发现被减数小于减数,就交换。
{
strcpy ( n , n1 ) ; //将n1数组的值完全赋值给n数组
strcpy ( n1 , n2 ) ;
strcpy ( n2 , n ) ;
swap ( lena , lenb ) ; //这步不能忘
printf ( "-" ) ; //别忘了输出负号
}
for ( i = 0 ; i < lena ; i ++ ) a [ lena - i ] = int ( n1 [ i ] - '0' ) ;
for ( i = 0 ; i < lenb ; i ++ ) b [ lenb - i ] = int ( n2 [ i ] - '0' ) ;
i = 1 ;
while ( i <= lena || i<= lenb )
{
if ( a [ i ] < b [ i ] ) //借位
{
a [ i ] += 10 ;
a [ i + 1 ] -- ;
}
c [ i ] = a [ i ] - b [ i ] ;
i ++ ;
}
int lenc = i ;
while ( c [ lenc ] == 0 && lenc > 1 ) lenc -- ; //最高位为0,则不输出
for ( i = lenc ; i >= 1 ; i -- ) printf ( "%d" , c [ i ] ) ;
return 0 ;
}