poj_1001 Exponentiation高精度乗算


Exponentiation
この問題の本質:高精度乗算を考察する.
注意点:注意!1.入力完了の判断;2.整数と小数部の出力.
以下にコードを添付します.注釈は比較的詳細です.
#include <stdio.h>
#define len 5

int init(int a[],int b[],char s[])
{
    int i,j;

    for (i=0;i<6;i++) if (s[i]=='.') break;
    for (j=0;j<i;j++) b[len-j]=s[j]-'0';
    for (j=i+1;j<6;j++) b[len-j+1]=s[j]-'0'; //change to numerical format

    for (j=1;j<=len;j++) a[j]=b[j];

    return len-i; //return the length of decimal part
}

void cal(int a[],int b[],int x)
{
    int n=x;

    while (x>1)
    {
        x--;
        int i,j,c[130]={0};

        for (i=1;i<=len*(n-x);i++) //high precision multiplication
            for (j=1;j<=len;j++)
        {
            c[i+j-1]+=a[i]*b[j];
            c[i+j]+=c[i+j-1]/10;
            c[i+j-1]%=10;
        }

        for (i=1;i<=len*(n-x+1);i++) a[i]=c[i];
    }
}

void print(int a[],int x,int y)
{
    int l_deci=x*y,l_int=len*y,i,j;

    for (i=l_int;i>0;i--) if (a[i]>0) break;
    for (j=i;j>l_deci;j--) printf("%d",a[j]); //print integral part

    for (i=1;i<=l_int;i++) if (a[i]>0) break;
    if (i<=l_deci)
    {
        printf(".");
        for (j=l_deci;j>=i;j--) printf("%d",a[j]);
    } //print decimal part

    printf("
"); } int main() { int n; char s[7]; while (scanf("%s%d",s,&n)!=EOF) { int a[130]={0},b[6]={0}; //a is the result, b is the base number int deci_len=init(a,b,s); //initialization cal(a,b,n); //calculate print(a,deci_len,n); //print out } return 0; }