求助!为什么全是WA!

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

Lindafish @ 2024-02-03 16:36:20

#include <stdio.h>

int main ( )
{
    int n,k;
    scanf("%d %d",&n,&k);
    int sumA,sumB;
    int countA=0,countB=0;
    int i;
    double av1,av2;
    for (i=2;i<=n;i++){
        if (i%k==0){
            countA++;
            sumA+=i;
        }else{
            countB++;
            sumB+=i;
        }
    }
    av1=sumA/countA;
    av2=sumB/countB;
    printf("%.1f %.1f",av1,av2);

    return 0;
}

by Max_LS @ 2024-02-03 22:26:09

SumA和SumB没有赋值为0。For循环是从2开始的。在计算平均值时,两个式子都没有乘以1.0。

#include <stdio.h>
int main ( )
{
    int n,k;
    scanf("%d %d",&n,&k);
    int sumA=0,sumB=0;
    int countA=0,countB=0;
    int i;
    double av1,av2;
    for (i=1;i<=n;i++){
        if (i%k==0){
            countA++;
            sumA+=i;
        }else{
            countB++;
            sumB+=i;
        }
    }
    av1=sumA*1.0/countA;
    av2=sumB*1.0/countB;
    printf("%.1f %.1f",av1,av2);

    return 0;
}

|