求助,为何数据精度上出现错误

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

Do1phln @ 2020-07-17 10:30:25

#include<iostream>
#include<cstdio>

using namespace std;

int main(){
    int n,k;
    cin>>n>>k;
    int a[10001],b[10001],ta = 0,tb = 0;
    int suma,sumb;
    double avea,aveb;
    for(int i = 1; i <= n;i++)
    {
        if(i%k == 0)
        {
            a[ta] = i;
            ta++;
        }
        else
        {
            b[tb] = i;
            tb++;
        }
    }
    for(int i = 0;i < ta; i++)
    {
        suma+=a[i];
    }
    for(int i = 0;i < tb; i++)
    {
        sumb+=b[i];
    }
    avea = suma / ta;
    aveb = sumb / tb;
    printf("%.1lf, %.1lf", suma / (double)ta, sumb / (double)tb);
    return 0;
}

求助各位大佬,为何跑样例时第二个数据结果为50.2QAQ


by fresh_boy @ 2020-07-17 10:34:20

double精度这种东西......我洛谷公开赛就掉过坑


by LX_Yao @ 2020-07-17 10:38:47

@OERROR 感觉你这写的好复杂啊


by 东方_east @ 2020-07-17 10:39:18

@OERROR 建议全部换成double试试


by LX_Yao @ 2020-07-17 10:50:44

@OERROR 建议你一开始就开double


by 星空记逸 @ 2020-07-17 11:01:25

计算平均数时*1.0试试

为啥要用数组


by Do1phln @ 2020-07-17 11:05:35

@星空记逸 *1.0后解决了,很奇怪啊,为什么会这样?


by LX_Yao @ 2020-07-17 11:11:30

@东方_east 同感


by Mr学霸君 @ 2020-07-17 11:12:21

不乘1.0或者乘1都是以int计算,转型也没有用


by LX_Yao @ 2020-07-17 11:12:46

@OERROR

printf("%.1lf, %.1lf", suma / (double)ta, sumb / (double)tb);

你试试double放在suma和sumb上面


by 东方_east @ 2020-07-17 11:12:56

@OERROR 因为一个算式里没有浮点型就会按整形计算就会自动向下取整精度就会有问题


| 下一页