关于精度问题

P10450 [USACO03MAR] Best Cow Fences G

Gcint @ 2024-11-13 20:08:59

请问为什么代码 solve 函数里,输出时候 int\ ans=rr*1000 就能AC,改成 int\ ans=mid*1000 就会WA一堆?

#include<bits/stdc++.h>
using namespace std;
const int maxx=1e5+5;
double n,ll,rr,mid,a[maxx],sum[maxx];
int l;
int read()
{
    int x=0,f=1;char c;
    c=getchar();
    while(c<'0'||c>'9')
    {
        if(c=='-') f=-1;
        c=getchar();
    }
    while('0'<=c&&c<='9')
    {
        x=x*10+c-'0';
        c=getchar();
    }
    return x*f;
}
bool check(double avg)
{
    double tmp=0.0;
    for(int i=1;i<=n;i++) sum[i]=sum[i-1]+a[i]-avg;
    for(int i=l;i<=n;i++)
    {
        tmp=min(tmp,sum[i-l]);
        if(sum[i]-tmp>=0) return true;
    }
    return false;
}
void init()
{
    ll=2005;
    n=read();l=read();
    for(int i=1;i<=n;i++)
    {
        a[i]=read();
        ll=min(ll,a[i]);
        rr=max(rr,a[i]);
    }
}
void solve()
{
    while(rr-ll>0.0000001)
    {
        mid=(ll+rr)/2.0;
        if(check(mid)) ll=mid;
        else rr=mid;
    }
    int ans=rr*1000;
    cout<<ans<<endl;
}
int main()
{
    //freopen("xxxx.in","r",stdin);
    //freopen("xxxx.out",."w",stdout);
    init();
    solve();
    return 0;
}

|