对精度问题的处理技巧

在Luogu分类中看到的有关精度问题的题目:

P2393 传送门 P2394 传送门

以前没有遇见过考这样知识点的题目……

1、浮点数的有效位数不满足要求时化为整型计算

一般来说$double$的有效位数为15~16位,$long double$的有效位数为18~19位

(注意,达到上界16/19位时并不保险,$double$有效值的确切上界为$2^{52}=4503599627370496$)

当题目要求的有效位数过高时,将浮点数乘上$10^n$化为整型计算

此时就可以使用高精度算法等处理整型大数的技巧来解决问题,最终答案再除以$10^n$即可

#include <bits/stdc++.h>

using namespace std;
typedef long double ld;
int main()
{
    ld x,res=0;
    while(scanf("%Lf",&x)!=EOF) res+=x*1e6;
    printf("%.5LF",res/1e6);
    return 0;
}

2、输入位数过多时会产生精度问题,要强制去除后面的位数

(我并不知道原因

注意$scanf$中说明符号前有一个读取长度参数可以设置

如$scanf( "\% 10d",\& n)$就只读取输入的前10个字符,后面的仍存在缓冲流里

#include <bits/stdc++.h>

using namespace std;
typedef long double ld;
int main()
{
    ld x;
    scanf("%15Lf",&x);
    printf("%.8Lf",x/23);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/newera/p/9278481.html