C++高精度減法模板

高精度減法要注意的是被減數必須必減數大,同時需要處理借位。方法類似於高精度加法。

#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 ;
}

相關鏈接:

C++模板小站:
https://blog.csdn.net/zj_mrz/article/details/80950647

C++高精度加法模板:
https://blog.csdn.net/zj_mrz/article/details/80948327

C++高精度乘法模板:
https://blog.csdn.net/zj_mrz/article/details/80967394

C++快速冪模板:
https://blog.csdn.net/zj_mrz/article/details/80950616

發佈了45 篇原創文章 · 獲贊 60 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章