现在的位置: 首页 > 综合 > 正文

zju1086 (高精度)解题报告

2014年02月24日 ⁄ 综合 ⁄ 共 1740字 ⁄ 字号 评论关闭

 

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;

}

 

 

抱歉!评论已关闭.