1001 Exponentiation

#include <stdio.h>
#include <string.h>
 
int len; // total length of exponentiation result
int product[126] = {0}; // storing result, at most length 5*25 + 1 = 126
 
void multiply(int a[], int n)
{
    int i;
    int carry = 0; // a carry number in multiplying
    for (i = 0; i < len; i++)
    {
        int temp = a[i]*n + carry;
        a[i] = temp % 10;
        carry = temp / 10;      
    }
    while (carry)
    {
        a[i++] = carry % 10;
        carry /= 10;
    }
    len = i;
}
 
int main(int argc, char* argv[])
{
    int n;  // power n
    char s[6]; // real number R, at most the length is 6
    while (scanf("%s %d", s, &n) != EOF)
    {
        int position=0, i=0, num=0, j=0; //position 为小数点位置
        for (i=0; i<strlen(s); i++) 
        {
            if (s[i] == '.')
            {
                position = (strlen(s) - 1 - i) * n; // calculate decimal point position after R^n   (eg:一个数有三位小数部分,三次方后有9位小数)
            }
            else
            {
                num = num*10 + s[i] - 48; // transfer char to integer('1' = 49)
            }       
        }
         
        // product calculation 
        product[0]=1;
        len = 1;
        for (i = 0; i < n; i++)
        {
            multiply(product, num);
        }
 
        // format output
        if (len <= position) // product is less than 1
        {
            printf("."); // print decimal point
            for (i=0; i<position-len; i++)
            {
                printf("0"); // print zero between decimal point and decimal
            }
 
            j = 0;
            //while (product[j] == 0) // trim trailing zeros
            //{
            //    j++;
            //}
            for (i=len-1; i>=j; i--)
            {
                printf("%d", product[i]);
            }
        }   
        else
        {
            j=0;
            while (product[j]==0 && j<position) // trim trailing zeros
            {
                j++;
            }
            for (i=len-1; i>=j; i--)
            {
                if (i+1 == position) // cause index in C language starts from 0
                {
                    printf(".");
                }
                printf("%d", product[i]);
            }
        }
        printf("\n");
    }

}



第一次发看看效果


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值