POJ 1001 Exponentiation

来源:互联网 发布:clipstudiopaint mac 编辑:程序博客网 时间:2024/06/16 09:45

高精度幂运算,详情见代码

#include <stdio.h>#include <string.h>int len;void multiply(int a[], int n){    int i;    int carry = 0;    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 n;     int product[126];    char s[7];    while (scanf("%s %d", s, &n) != EOF)    {        int position = 0, i = 0, num = 0, j = 0;        for (i = 0; i<strlen(s); i++)        {            if (s[i] == '.')//去掉小数点            {                position = (strlen(s) - 1 - i) * n;            }            else            {                num = num * 10 + s[i] - 48;//把字符串中的小数转化成一个整数            }        }        product[0] = 1;//初始化结果的最后一位为1,因为进行multiply运算时是从后往前算的        len = 1;        for (i = 0; i < n; i++)        {            multiply(product, num);        }        if (len <= position) //无整数部分        {            printf(".");            for (i = 0; i<position - len; i++)//在输出product前补够0            {                printf("0");             }            j = 0;            while (product[j] == 0)//去除后导0            {                j++;            }            for (i = len - 1; i >= j; i--)            {                printf("%d", product[i]);            }        }        else        {            j = 0;            while (product[j] == 0 && j<position) //去掉前导0            {                j++;            }            for (i = len - 1; i >= j; i--)//循环i>=j保证不输出后导0            {                if (i + 1 == position)                 {                    printf(".");                }                printf("%d", product[i]);            }        }        printf("\n");    }    return 0;}
0 0
原创粉丝点击