题目:
Octal Fractions
Time Limit: Java: 2000 ms / Others: 2000 ms
Memory Limit: Java: 65536 KB / Others: 65536 KB
[显示标签]
Description
Fractions in octal (base 8) notation can be expressed exactly in decimal notation. For example, 0.75 in octal is 0.963125 (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
0.d1d2d3 … dk [8] = 0.D1D2D3 … Dm [10]
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.
Sample Input
0.75
0.0001
0.01234567
Sample Output
0.75 [8] = 0.953125 [10]
0.0001 [8] = 0.000244140625 [10]
0.01234567 [8] = 0.020408093929290771484375 [10]
题目大意:
给出一个八进制的数,然后让我们把这个八进制的数精确的转化为十进制的数,给出的数的范围在 (0, 1) 之间。
解题思路:
首先我们可以想到 (0.75)8 = 7 / 8 + 5 / 8 / 8 = ( (5 / 8) + 7 ) / 8;
第二个式子中的8是累乘的,所以我们就可以转化为高精度除以 8;
实现的细节:
我们每次从给出的小数的最后一位往前去计算,例如 0.75 这个例子,我们首先用一个src字符串去接受这个小数,然后第一次得到的是5这个字符,用num来保存每次src的字符,然后我们通过一个循环,每次 tmp = num * 10 + (j < idx ? dest[j] - ‘0’ : 0),来获得每次的被除数,在这个num相当于是于是余数,这样我们就实现了 小数的最高位只除了一次8,第二位除了2次8,…
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 105;
char src[maxn];
int main(void) {
// freopen("in.txt", "r", stdin);
while(scanf("%s", src) != EOF) {
int i, j, idx = 0;
char dest[maxn] = {'0'};
for(i = strlen(src) - 1; i >= 2; i --) {
int num = src[i] - '0';
int tmp;
for(j = 0; j < idx || num; j ++) {
tmp = num * 10;
if(j < idx) tmp += dest[j] - '0';
dest[j] = tmp / 8 + '0';
num = tmp % 8;
}
idx = j;
}
dest[j] = '\0';
printf("%s [8] = 0.%s [10]\n", src, dest);
}
// fclose(stdin);
return 0;
}