参考链接
输入描述:
多组测试用例,请参考例题的输入处理 输入每行一个浮点数 R 其中0.0 < R <99.999, 一个整数 n 其中0 < n <=25
输出描述:
输出R的n次方
输入例子1:
95.123 12 0.1 1
输出例子1:
548815620517731830194541.899025343415715973535967221869852721 0.1
解题思路
因为涉及到的操作数可能会非常大,超出c语言本身能表示的数的大小以及精度,所以思路大概是这样的:
1、对输入的处理,因为第一个书可能是小数,小数相乘我们要记录下小数点的位置,所以第一个输入按字符串格式读入,通过比较找出小数点的位置。
2、对R的处理,小学时我们学小数的计算的时候,都是先转换成整数,记下两个乘数的小数点的位置,最后再加上小数点,所以先把R处理成整数,并通过小数点的位置计算出最后结果的小数位数。
3、计算,计算按大数计算的方式进行计算。
4、输出,输出的时候要检查最后结果是否小于1,小于1的话,要补充足够的0
#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 = 126void multiply(int a[], int n)
{int i;int carry = 0; // a carry number in multiplyingfor (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 nchar s[6]; // real number R, at most the length is 6while (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; // calculate decimal point position after R^n}else{num = num*10 + s[i] - 48; // transfer float to integer} }// product calculation product[0]=1;len = 1;for (i = 0; i < n; i++){multiply(product, num);}// format outputif (len <= position) // product is less than 1{printf("0");printf("."); // print decimal pointfor (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");}
}