NewCode----給定兩個數R和n,輸出R的n次方
阿新 • • 發佈:2018-11-22
輸入描述:
多組測試用例,請參考例題的輸入處理 輸入每行一個浮點數 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 = 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;
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 output
if (len <= position) // product is less than 1
{
printf("0");
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");
}
}