现在的位置: 首页 > 综合 > 正文

HDOJ 1063 Exponentiation(小数高精度)

2019年02月12日 ⁄ 综合 ⁄ 共 681字 ⁄ 字号 评论关闭

小数的幂,就是太麻烦。c++手写高精度。

#include<stdio.h>
#include<string.h>
#include<math.h>
#define MAX 100000

const double eps = 1e-12;

int main()
{
    int n, i, j, flag, d, s;
    int a[MAX];
    double t;
    
    while (scanf("%lf %d", &t, &n) != EOF)
    {
        int c = 0;
        
        if ((int)t == 0) 
            flag = 0;
        else 
            flag = 1;
        
        t += eps; //由于double储存特性,0.4321储存会储存为0.4320999999999
        
        while (fabs((int)t - t) > 1e-5)
        {
            t *= 10;
            c ++;
            if (c == 5) break;
        }
        
        s = (int)t;
        memset(a, 0, sizeof(a));
        d = 1;
        a[0] = 1;
        
        for (i = 0; i < n; i ++)
        {
            for (j = 0; j < d; j ++)
                a[j] = a[j] * s;
            for (j = 0; j < d; j ++)
            {
                if (a[j] > 9)
                {
                    if (j == d - 1)
                        d ++;
                    a[j+1] += a[j] / 10;
                    a[j] = a[j] % 10;
                }
                
            }
        }
        if (d <= c * n && flag == 0)
        {
            printf(".");
            for (j = 0; j < c * n - d; j ++)
                printf("0");
            for (i = d - 1; i >= 0; i --)
                printf("%d", a[i]);
        }
        else
        {
            for (i = d - 1; i >= 0; i --)
            {
                if (i + 1 == c * n)
                    printf(".");
                printf("%d", a[i]);
            }
        }
        printf("\n");
    }
    return 0;
}

抱歉!评论已关闭.