描述
Fractions in octal (base 8) notation can be expressed exactly in decimal notation. For example, 0.75 in octal is 0.953125 (7/8 + 5/64) in decimal. All octal numbers of n digits to the right of the octal point can be expressed in no more than 3n decimal digits to the right of the decimal point.
Write a program to convert octal numerals between 0 and 1, inclusive, into equivalent decimal numerals.
输入
The input to your program will consist of octal numbers, one per line, to be converted. Each input number has the form 0.d1d2d3 ... dk, where the di are octal digits (0..7). There is no limit on k.
输出
Your output will consist of a sequence of lines of the form
where the left side is the input (in octal), and the right hand side the decimal (base 10) equivalent. There must be no trailing zeros, i.e. Dm is not equal to 0.
样例输入
0.75
0.0001
0.01234567
样例输出
0.75 [8] = 0.953125 [10]
0.0001 [8] = 0.000244140625 [10]
0.01234567 [8] = 0.020408093929290771484375 [10]
题目来源
题目意思就是把小数位的八进制转换为十进制。
【转换方法】
例如:0.01234567
则是0/(8)+1/(8*8)+2/(8*8*8)+3/(8*8*8*8)+...+7/(8*8*8*8*8*8*8*8)=0.020408093929290771484375
因为要转换的数字挺大的所以要用数组来存放小数位,另外计算的公式也转换为:((((7/8+6)/8+5)/8+4)/8+...+0)/8
#include <stdio.h> #include <string.h> #define MAXN 10000 char d[MAXN]; int D[MAXN]; int main() { int cnt;//表示当前数组存放的位置 int next; int current; while(gets(d)!=NULL){ int len=strlen(d); int Dlen=0; memset(D,0,sizeof(D)); for(int i=len-1; i>=2; i--){ cnt=0; int num=d[i]-'0'; next=num; while(next!=0 || cnt<Dlen){ current=next*10+D[cnt]; D[cnt++]=current/8; next=current%8; } Dlen=cnt; } printf("%s [8] = 0.",d); for(int i=0; i<cnt; i++){ printf("%d",D[i]); } printf(" [10] "); } return 0; }