UVa 11809 - Floating-Point Numbers

十进制转二进制存储需要几位

m*2^e=a*10^b;
log10(m)+e*log10(2)=log10(a)+b;
m=1-2^(-i-1)
e=2^j-1

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
double f[10][35];
char s[100];
double a,c;
int b;
void fuc()
{
    double m=1,e;
    for(int i=0;i<=9;++i)
    {
        m/=2;
        e=1;
        for(int j=0;j<=30;++j)
        {
            f[i][j]=log10(1-m)+log10(2)*(e-1);//用log存储 
            e*=2; 
        }
    }
}
int main()
{
    fuc();
    while(~scanf("%s",s)&&strcmp(s,"0e0"))
    {
        s[17]=' ';
        sscanf(s,"%lf%d",&a,&b);
        c=log10(a)+b; 
        for(int i=0;i<=9;i++)
        {
            for(int j=0;j<=30;j++)
            {
                if(fabs(c-f[i][j])<1e-7)
                {
                    cout<<i<<' '<<j<<endl;
                    break;
                }
            }
        }
    }
    return 0;
} 

 

posted @ 2016-03-29 23:59  nicetomeetu  阅读(210)  评论(0编辑  收藏  举报