C++ 20分

B2095 白细胞计数

lanlfd @ 2022-11-22 08:05:53

#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
    int n;
    double max = 0.0, min = 1.0e6, sum = 0.0, avg, err = -1.0;
    double x[520];
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> x[i];
    }
    for (int i = 0; i < n; i++)
    {
        if (x[i] > max)max = x[i];
        if (x[i] < min)min = x[i];
    }
    for (int i = 0; i < n; i++)
    {
        if ((x[i] != max) && (x[i] != min))
            sum = sum + x[i];
    }
    avg = sum / (n - 2);
    for (int i = 0; i < n; i++)
    {
        if ((x[i] != max) && (x[i] != min))
        {
            double a = x[i] - avg;
            if (fabs(a) > err)
                err = fabs(a);
        }
    }
    cout << fixed << setprecision(2) << avg << " ";
    cout << fixed << setprecision(2) << err;
    return 0;
}

by DERMING @ 2022-11-22 09:45:34

这个样子就对啦

#include<bits/stdc++.h>
using namespace std;
double x[10000];
int main()
{
    int n;
    cin >> n;
    for (int i = 1; i <=n; i++)
    {
        cin >> x[i];
    }
    sort(x+1,x+1+n);
    double sum=0;
    for (int i = 2; i <n; i++)
    {
        sum+=x[i];
    }
    double ave =sum / (double)(n - 2);
    double maxx=-1;
    for (int i = 2; i <n; i++)
    {
        maxx=max(maxx,fabs(x[i]-ave));
    }
    printf("%.2lf %.2lf",ave,maxx);
    return 0;
}

问题

  1. 计算太麻烦,排序然后循环从第二个开始到倒数第二个结束即可
  2. 计算差值时要掐头去尾
  3. 输出可以用printf格式化输出
  4. 变量命名不要用max,可以用maxx,maxn等代替(time,next...都不行)
  5. 改善一下码风吧……孩子看得脑子都要炸了

by DERMING @ 2022-11-24 14:23:09

@lanric 看上面


by lanlfd @ 2022-11-25 23:07:28

好的谢谢。


by Rume152 @ 2023-01-25 14:55:27

为什么搞一个maxx = -1 和 fabs比较?


by Rume152 @ 2023-01-25 15:47:32

为什么sort第一个参数是x+1不是x ,x和x+1好像都能ac


|