小数字没问题,大数字会出现计算不准确的问题,是数据类型的问题吗

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

xiaocongst @ 2024-02-13 11:59:08

#include<stdio.h>
int main()
{
    int n, k, i;
    float  a = 0, b = 0, x = 0;
    scanf("%d%d", &n, &k);
    while (n <= k || n < 1 || n>10000 || k < 1 || k>100)scanf("%d%d", &n, &k);
    for (i = 1;i <= n;i++)
    {
        if (i % k == 0)
        {
            a = a + i;
            x++;
        }
        else
        {
            b = b + i;
        }
    }
    double A, B;
    A = a / x;
    B = b / (n - x);
    printf("%.1f %.1f", A, B);
    return 0;
}

by wangruiqi36 @ 2024-02-13 12:15:18

@xiaocongst

应该是float的精度问题

int  a = 0, b = 0, x = 0;
//...
A = (double)a / x;
B = (double)b / (n - x);

这样可以过

double  a = 0, b = 0, x = 0;

也可以过


by _buzhidao_ @ 2024-02-13 12:15:24

@xiaocongst float改成double


by zszfympxdebug @ 2024-02-13 12:56:06

改成lf


|