求助代码问题

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

Lucky7777 @ 2024-04-03 22:37:21

哪位大佬能帮我看看吗?80分真不知道错哪了 球球了谢谢```c

include <stdio.h>

void pingjun(int sum,int size){ int u,v; u=sum/size; v=sum10/size-u10; printf("%d.%d",u,v); }

int main(){

int n,k,sum_a=0,sum_b=0,sum=0,size_a=0,size_b=0;
scanf("%d%d",&n,&k);
for(int i=k;i<=n;i=i+k){
    sum_a=sum_a+i;
    size_a++;
}
sum=(1+n)*n/2;
sum_b=sum-sum_a;
size_b=n-size_a;

pingjun(sum_a,size_a);
printf(" ");
pingjun(sum_b,size_b);

return 0;

}


by Lucky7777 @ 2024-04-03 22:52:45

稍改了还不行

#include <stdio.h>

void pingjun(int sum,int size){
    int u,v;
    u=sum/size;
    v=sum*10/size-u*10;
    if((sum*100/size-u*100-v*10)>=5){
        v=v+1;
    }
    printf("%d.%d",u,v);
}

int main(){

    int n,k,sum_a=0,sum_b=0,sum=0,size_a=0,size_b=0;
    scanf("%d%d",&n,&k);
    for(int i=k;i<=n;i=i+k){
        sum_a=sum_a+i;
        size_a++;
    }
    sum=(1+n)*n/2;
    sum_b=sum-sum_a;
    size_b=n-size_a;

    pingjun(sum_a,size_a);
    printf(" ");
    pingjun(sum_b,size_b);

    return 0;
}

by elsc @ 2024-04-04 07:03:47

建议使用printf,把pingjun改成:

void pingjun(int sum, int size) {
  printf("%.1lf", (double)sum / size);
}

by elsc @ 2024-04-04 07:21:41

@Lucky7777 sum最大值可以是50005000, pingjun函数中四舍五入乘100会超出int的最大表示范围2147483647从而溢出。 建议在进行实数运算时不要自己用整型处理, 直接使用浮点数。浮点数其实非常快, 比用整数模拟快多了。


by Lucky7777 @ 2024-04-06 21:09:20

@Lzl_Doctor 好的好的 非常感谢!!!!!


|