初学者 40分 求助 哪里的错误

P5719 【深基4.例3】分类平均

Mercurysinklee @ 2020-05-27 14:28:30

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,k,s=0,m=0;
    int a=0,b=0;
    cin>>n>>k;
    for(int i=1;i<=n;i++)
    {
        if(i%k==0)
        {
            s+=i;
            a++;
        }
        else if(i%k!=0)
        {
            m+=i;
            b++;
        }
    }
    if(k==0)
    {
        cout<<0.0<<" "<<0.0;
    }
    if(a==0)
    {
        cout<<0.0<<" "<<setprecision(1)<<fixed<<(double)(m/b)<<endl;
    }
    if(b==0)
    {
        cout<<setprecision(1)<<fixed<<(double)(s/a)<<" "<<0.0<<endl;
    }
    cout<<setprecision(1)<<fixed<<(double)(s/a)<<" "<<(double)(m/b)<<endl;
    return 0;
}

by maoyiting @ 2020-05-27 15:07:33

您这个好像样例都没过/jk

(double)(s/a)改成1.0*s/a,把(double)(m/b)改成1.0*m/b试试康~


by maoyiting @ 2020-05-27 15:17:47

因为s/a是下取整的,然后您转成double是把s/a的下取整转成了double。举个栗子,3/2 的下取整是 1,然后转成double是 1 的double类型,但其实答案是1.5,但是您用1.0*3/2就没有这个问题,或者用(double)3/(double)2

您可以自己尝试一下~


by Mercurysinklee @ 2020-05-27 17:29:28

@maoyiting 啊啊啊啊谢谢谢谢!明白了谢谢您!!!


|