求助

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

空kong @ 2020-10-06 22:06:04

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    int n,
        k,
        i,
        h1 = 0, h2 = 0,
        j = 0,t = 0;
    double a,
           b;
    scanf("%d %d", &n, &k);
    for (i = 1; i <= n; i++)
    {
        if (i % k == 0)
        {
            h1 = h1 + i;
            j++;
        }
        else
        {
            h2 = h2 + i;
            t++;
        }
    }
    printf("%.1lf %.1lf", a = h1 / j, b = h2 / t);
    return 0;
}

为什么只有四十分


by cheating_dictator @ 2020-10-06 22:19:54

h1,h2,j,t都是整型,除得结果是整数

类型转换:

printf("%.1lf %.1lf", (double) h1 / j, (double) h2 / t);

by 空kong @ 2020-10-06 22:32:48

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    int n,
        k,
        i,
        h1 = 0, h2 = 0,
        j = 0,t = 0;
    double a,
           b;
    scanf("%d %d", &n, &k);
    for (i = 1; i <= n; i++)
    {
        if (i % k == 0)
        {
            h1 = h1 + i;
            j++;
        }
        else
        {
            h2 = h2 + i;
            t++;
        }
    }
    a = h1 / j;
    b = h2 / t;
    printf("%.1lf %.1lf", a, b);
    return 0;
}

为什么这个也不行


by 空kong @ 2020-10-06 22:33:41

@cheating_dictator


by cheating_dictator @ 2020-10-06 22:35:09

应该用double定义h1,h2,t,j


|