求助,不理解了

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

zhaoanqiEtayo @ 2023-07-08 06:24:53

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int n,k,i,sum1,sum2,a,q;
    double b,c;
    scanf("%d %d",&n,&k);
    sum1=0;sum2=0;
    a=0;q=0;
    for(i=1;i<=n;i++)
    {
        if(i%k==0)
        {
            a++;
            sum1=sum1+i;
            b=sum1/a*1.0;
        }
        else
        {
            q++;
            sum2=sum2+i;
            c=sum2/q*1.0;
        }
    }
    printf("%.1lf %.1lf",b,c);
    return 0;
}

by zhongboxuan123 @ 2023-07-08 06:46:25

@zhaoanqiEtayo 把bq的计算放到循环外


by zhaoanqiEtayo @ 2023-07-08 09:13:12

@zhongboxuan123 谢谢!但可以解释一下为什么这样写吗?萌新不理解


by zhaoanqiEtayo @ 2023-07-08 09:16:15

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int n,k,i,sum1,sum2,a,q;
    double b,c;
    scanf("%d %d",&n,&k);
    sum1=0;sum2=0;
    a=0;q=0;
    for(i=1;i<=n;i++)
    {
        if(i%k==0)
        {
            a++;
            sum1=sum1+i;
        }
        else
        {
            q++;
            sum2=sum2+i;
        }
    }
    b=sum1/a*1.0;
    c=sum2/q*1.0;
    printf("%.1lf %.1lf",b,c);
    return 0;
}

@zhongboxuan123 好像还是不对呀


by zhongboxuan123 @ 2023-07-08 10:03:16

@zhaoanqiEtayo 精度丢失问题,用你的代码输出1000 7这组数据的时候输出了500.0,说明精度丢失,我给出的建议是把aq改成double,然后先1.0,后面`b=sum1/a1.0; c=sum2/q*1.0;就不用再乘了`


by zhongboxuan123 @ 2023-07-08 10:03:50

@zhaoanqiEtayo 这是通过记录1


by zhaoanqiEtayo @ 2023-07-08 10:19:30

@zhongboxuan123 感谢


by Griseo1221 @ 2023-07-31 15:15:55

@zhaoanqiEtayo 我超 穹


|