为什么float数据类型就不可以

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

ATYXXA @ 2020-10-12 23:41:18

这是100分的代码

#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
    int n, k;
    cin >> n >> k;
    double sumA = 0, sumB = 0, numA = 0, numB = 0;

    for (int i = 1; i <= n; i++)
    {
        if (i % k == 0)
        {
            sumA += i;
            numA++;
        }
        else
        {
            sumB += i;
            numB++;
        }
    }

    double aveA, aveB;
    aveA = sumA / numA;
    aveB = sumB / numB;

    cout <<fixed<< setprecision(1) << aveA << " " <<fixed<< setprecision(1) << aveB;

    return 0;
 }

这是40分的代码


 #include<iostream>
#include<iomanip>
using namespace std;

int main()
{
    int n, k;
    cin >> n >> k;
    float sumA = 0, sumB = 0, numA = 0, numB = 0;//按道理用float和double区别应该不大的,但不知道为什么只有40分

    for (int i = 1; i <= n; i++)
    {
        if (i % k == 0)
        {
            sumA += i;
            numA++;
        }
        else
        {
            sumB += i;
            numB++;
        }
    }

    float aveA, aveB;//还有这里
    aveA = sumA / numA;
    aveB = sumB / numB;

    cout <<fixed<< setprecision(1) << aveA << " " <<fixed<< setprecision(1) << aveB;

    return 0;
 }

by Eason_AC @ 2020-10-13 00:26:28

应该是精度问题吧(


by 林聪 @ 2020-10-13 01:32:46

float精度低,一般还是建议使用double


by Smile_Cindy @ 2020-10-13 09:42:04

@ATYXXA

float精度太低了,建议double


|