11809 - Floating-Point Numbers (UVA)

题目链接如下:

Online Judge

这道题目我想到了打表做,但是没想到用log来简化……写了一个比较复杂的版本,严重超时。后来看了别人的题解才做出来。UVa 11809 Floating-Point Numbers(浮点数)_ShannonNansen的博客-CSDN博客

我的代码如下:

#include <iostream>
#include <string>
#include <cmath>
const double EPS = 0.0001;

std::string str;
int E, temp;
double M, t, a;
double ans1[10][31];
int ans2[10][31];

int main(){
    for(int i = 0; i <= 9; ++i){
        M = 1 - 1.0 / (1 << (i + 1));
        for(int j = 1; j <= 30; ++j){
            E = (1 << j) - 1;
            t = log10(M) + E * log10(2);
            ans2[i][j] = t;
            ans1[i][j] = pow(10, t - ans2[i][j]);
        }
    }
    while(std::cin >> str && str != "0e0"){
        a = std::stod(str.substr(0, 17));
        temp = std::stoi(str.substr(18));
        for(int i = 0; i <= 9; ++i){
            for(int j = 1; j <= 30; ++j){
                if(ans2[i][j] == temp && fabs(a - ans1[i][j]) < EPS){
                    printf("%d %d\n", i, j);
                    i = 10;
                    break;
                }
            }
        }
    }
    return 0;
}

我严重超时的版本如下:

#include <iostream>
#include <string>
#include <cmath>

std::string str;
int M, E, t, temp, power, prevpower;
double a, tempa, b, k, preva;
double ans1[10][31];
int ans2[10][31];

int main(){
    a = 0;
    k = 1;
    for(M = 0; M <= 9; ++M){
        k *= 0.5;
        a += k;
        t = 0;
        for(E = 1; E <= 30; ++E){
            temp = t + 1;
            t = 2 * t + 1;
            tempa = E == 1 ? a : preva;
            power = E == 1 ? 0 : prevpower;
            while(temp){
                while(tempa < 10 && temp){
                    tempa *= 2;
                    temp--;
                }
                if(tempa >= 10){
                    tempa /= 10;
                    power++;
                }
            }
            preva = tempa;
            prevpower = power;
            ans1[M][E] = tempa;
            ans2[M][E] = power;
        }
    }
    while(std::cin >> str && str != "0e0"){
        a = std::stod(str.substr(0, 17));
        temp = std::stoi(str.substr(18));
        for(M = 0; M <= 9; ++M){
            for(E = 1; E <= 30; ++E){
                if(ans2[M][E] == temp && fabs(a - ans1[M][E]) < 0.0001){
                    printf("%d %d\n", M, E);
                    M = 10;
                    break;
                }
            }
        }
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值