b193簡單

96 雲嘉區資訊學科能力競賽(2007)|去極值平均

將五個整數排序,保留索引1、2、3的三個值。

解題思路

將五個整數排序,保留索引1、2、3的三個值。

它們的總和S除以3即為平均;百分位的四捨五入可用(abs(S)×100+1)//3,再補回符號。因分母3,不會恰好半分。

以整數部分與兩位餘數組合輸出,支援負數且避免浮點誤差。

五數固定,時間空間 O(1),任意精度運算成本依輸入位數。

Step-by-step animation

教學小例:只刪一個最大與一個最小

回報動畫錯誤
步驟 1 / 3

輸入1,1,1,1,9

排序後刪掉一個1及9

排序後刪掉一個1及9
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
int main() {
    vector<cpp_int> a(5);
    for (auto &x : a)
        cin >> x;
    sort(a.begin(), a.end());
    cpp_int s = a[1] + a[2] + a[3];
    bool neg = s < 0;
    if (neg)
        s = -s;
    cpp_int c = (s * 100 + 1) / 3;
    if (neg && c != 0)
        cout << '-';
    cout << c / 100 << '.';
    int rem = (c % 100).convert_to<int>();
    cout << setw(2) << setfill('0') << rem << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多