uva - 11809 - Floating-Point Numbers

传送门:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2909

由于M和E的取值范围很小,一共就有300种情况,可以先计算出所有的情况,打个表,然后查表就行了。另外,浮点数比较大小有误差,所有在比较浮点数的时候,只要两个数的差小于1e-5就可以认为相等了。

代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
double M[11][33];
long long E[11][33];
void solve(double m,long long e);

int main()
 {
    int i, j;
    double m, t;
    long long e;
    char str[22];
    for(i = 0; i <= 9; i++)
        for(j = 1; j <= 30; j++)
        {
            e = (1 << j) - 1;
            m = 1 - 1.0 / (1 << (i + 1));
            t = log10(m) + e * log10(2);
            E[i][j] = t / 1;
            M[i][j] = pow(10, t - E[i][j]);
        }
    while(cin >> str, strcmp(str,"0e0"))
    {
        *(strchr(str,'e')) = ' ';
        sscanf(str,"%lf %lld", &m, &e);
        solve(m, e);
    }
    return 0;
}
void solve(double m,long long e)
{
    int i, j;
    for(i = 0; i <= 9; i++)
        for(j = 1; j <= 30; j++)
            if(e == E[i][j] && fabs(m - M[i][j]) < 1e-5)
            {
                cout<<i<<" "<<j<<endl;
                return;
            }
}

你可能感兴趣的:(uva)