zju1086 (高精度)解題報告

 

Octal Fractions


Time Limit: 1 Second      Memory Limit: 32768 KB


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]

題目大一就是說給一個8進制的數,求出對應的十進制數,按題目要求來看最先想到得就是用每一位除以對應的8的冪,但是很顯然,會受到精度的影響,所以可以換一種思路,例如,0.75【8】=((5/8)+7)/8【10】,所以之後就只要模擬除法進行高精度計算就可以了。

代碼:

語言:c++

 

#include<iostream>

#include<cstring>

#include<cstdlib>

using namespace std;

int main()

{

char result[10000],a[10000];//result[]是十進制數結果,a[]是輸入的8進制數

int count,len,i,j,num,temp;//len是8進制數的長度,count是十進制數的長度,num是每次取8進制數的一位轉化成的整型數

while(scanf("%s",a)!=EOF)

{

count=0;//十進制數一開始的長度爲0

len=strlen(a);

for(i=0;i<10000;++i)

result[i]='0';      //每次都先將結果數組置0

for(i=len-1;i>=2;--i)//從8進制數的最後一位開始取,進行高精度除法

{

num=int(a[i])-'0';//num用來存放整型數

for(j=0;j<count||num;++j)//判斷條件爲j超過十進制數的長度和num=0,即直到num除盡

{

if(j<count)

temp=num*10+(int(result[j])-'0');

else

temp=num*10;

result[j]=char(temp/8)+'0';//商

num=temp%8;//餘數

}

result[j]='/0';//設置result數組的結尾標誌符,以便輸出和求長度;

count=strlen(result);//count爲result數組的長度即十進制數的當前長度

}

cout<<a<<" [8] = 0."<<result<<" [10]"<<endl;

}

return 0;

}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章