为什么long double 95而double 100呢?

B2054 求平均年龄

Dian_ed @ 2023-02-24 20:30:20

//2022tysc0784
#include<iostream>
#include<iomanip>
using namespace std;
long long nn,n;
double nnn;
int main(){
    cin>>nn;
    for(int i=1;i<=nn;i++){
        cin>>n;
        nnn+=n;
    }
    cout<<setprecision(2)<<fixed<<nnn/nn;
}

以上的代码,在定义nnn时,如果是double就满分,而long double就95,这是为什么啊?


by ragwort @ 2023-02-24 20:35:16

@2022TYSC0784 你用 long long 的代码是什么?


by Dian_ed @ 2023-02-24 20:39:35

@wind_kaka

long double,不是long long

//2022tysc0784
#include<iostream>
#include<iomanip>
using namespace std;
long long nn,n;
long double nnn;
int main(){
    cin>>nn;
    for(int i=1;i<=nn;i++){
        cin>>n;
        nnn+=n;
    }
    cout<<setprecision(2)<<fixed<<nnn/nn;
}

by ragwort @ 2023-02-24 20:40:13

@2022TYSC0784 精度问题吧,double 本来就能存很大


by baoziwu2 @ 2023-02-24 20:43:36

@wind_kaka 那不是很奇怪吗,double能存的精度long double反而存不了(


by baoziwu2 @ 2023-02-24 20:59:04

很奇怪,一般是 double 加精度误差才能比上long double 有没有一种微弱的可能性是题目数据是用double造的

#include <iostream>
#include <iomanip>

using namespace std;

long double const eps = 1e-8;

long long n, x;
long double sum;

int main() {
    cin >> n;
    for(int i = 1; i <= n; i++) {
        cin >> x;
        sum += x;
    }
    printf("%.2Lf", (sum + eps) / n);
}

但是保留两位小数不大可能会有误差吧


by Dian_ed @ 2023-02-24 21:04:05

@baoziwu2 有可能


|