我不知道怎么控制小数点后一位的精度

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

Langrange2021 @ 2021-10-30 16:07:05

#include <stdio.h>
int main()
{
    int k, n,count1=0,count2=0,sum1=0,sum2=0,count;
    double average1, average2;
    scanf("%d %d", &n, &k);
    int C = k;
    while (C <= n)
    {
        if (C % k == 0)
        {
            sum1 += C;
            count1++;
        }
        else
        {
            sum2 += C;
            count2++;
        }
        C++;
    }
    average1 = sum1 / count1;
    for (count = 1; count <= (k - 1); count++)
    {
        sum2 += count;
    }
    average2 = sum2 / (count2+k-1);
    printf("%.1f %.1f", average1, average2);
    return 0;
    }

求助各位大佬,教教我这个刚学一个月的蒟蒻


by 我送送送送 @ 2021-10-30 16:08:34

double%.1lf


by Langrange2021 @ 2021-10-30 16:29:43

@我送送送送 不行啊dl,还是不对


by Langrange2021 @ 2021-10-30 16:30:29

@我送送送送 应该不是这里的问题


by ashelly @ 2021-10-31 15:45:06

我也是!就是不知道第二例后面的.1怎么得出来的同求大佬解答


by 我送送送送 @ 2021-11-01 14:08:58

average1 = sum1 *1.0/ count1;

average2 = sum2 *1.0/ (count2+k-1);

printf("%.1f %.1f", average1, average2);


by Langrange2021 @ 2021-11-05 16:27:23

@我送送送送 我通过了,感谢大佬


by cccyz @ 2021-12-11 11:03:04

@我送送送送 大佬为什么*1.0就行了。。。不理解


by 我送送送送 @ 2021-12-11 16:00:14

@cccyz

sum1,sum2,count1和count2都是整数,直接除以C++会默认取整

在C++中,\times1.0可以让整数变为浮点数(float,double),而在C++的除法中,只要被除数与除数中至少一个为浮点数,就可以使结果为浮点数

所以,\times1.0的目的就是是结果为浮点数


by cccyz @ 2021-12-11 16:31:33

@我送送送送 懂了,感谢大佬


|