大數加法、乘法

來源:互聯網
上載者:User

標籤:style   blog   http   color   java   os   io   for   

  1 #include<iostream>  2   3 #include<stdio.h>  4   5 #include<string.h>  6   7 #define Len 3000//大數的長度  8   9 using namespace std; 10  11 int Input (char n[])//將大數讀入的函數 12  13 { 14  15     char s[Len]; 16  17     int i,l; 18  19   20  21     for(i=0; i<Len; i++) n[i]=0; 22  23     if(scanf("%s",s)<1) return -1; 24  25     l= strlen(s); 26  27     for(i=0; i<l; i++) //將輸入的大數逆置 28  29         n[i]=s[l-i-1]-‘0‘; 30  31   32  33 } 34  35 int Print (char n[]) 36  37 { 38  39     int i; 40  41     for(i=Len-1; i>0; i--) 42  43         if(n[i]!=0) break; 44  45     for(; i>=0; i--) 46  47         printf("%d",n[i]); 48  49     printf("\n"); 50  51 } 52  53   54  55 void Add (char a[],char b[],char c[])//大數加法 56  57 { 58  59     int i=0; 60  61     for(i=0; i<Len; i++) 62  63         c[i]=a[i]+b[i]; 64  65     for(i=0; i<Len; i++) //處理進位 66  67     { 68  69         if(c[i]>=10) 70  71         { 72  73             c[i+1]+=c[i]/10; 74  75             c[i]=c[i]%10; 76  77         } 78  79     } 80  81 } 82  83 void Mul(char a[],char b[],char c[])//大數乘法 84  85 { 86  87     int i,j; 88  89     int alen=strlen(a),blen=strlen(b); 90  91     for(i=0; i<Len; i++) c[i]=0; 92  93     for(i=0; i<alen; i++) 94  95         for(j=0; j<blen; j++) //處理進位 96  97         { 98  99             c[i+j]+=a[i]*b[j];100 101             if(c[i+j]>=10)102 103             {104 105                 c[i+j+1]+=c[i+j]/10;106 107                 c[i+j]%=10;108 109             }110 111         }112 113 }114 115 int main()116 117 {118 119     char a[Len],b[Len],c[Len];120 121     Input(a);122 123     Input(b);124 125     Add(a,b,c);126 127     Print(c);128 129     Mul(a,b,c);130 131     Print(c);132 133     return 0;134 135 }

這是最好理解的一種寫法,不過好像用java寫高精度會簡單很多,等學了java之後再補充

還有個部落格寫得很多....但不好理解 http://www.cnblogs.com/heyonggang/p/3599857.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.