題目連結地址 10137 - The Trip
/** 10137 - The Trip* 作者 儀冰* 語言 C++* QQ 974817955** 精度處理一小弄。n個學生,每個學生有一個花費,* 求出平均值,求小於平均值的總和(less),* 求出大於平均值的總和(greatly),最後再進行less和grealy比較,輸出最大的。*/#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int SIZE = 1000;const double EXP = 1e-8;int main(){ int nStudents = 0; //學生總數 double everyStudentCost[SIZE]; //儲存每個學生的花費 double totalCost = 0.0; //花費總數 double average = 0.0; //平均值 double less = 0.0; //少於平均值 double greatly = 0.0; //多於平均值 while (cin >> nStudents) { if (nStudents == 0) { break; } //初始化 totalCost = 0.0; average = 0.0; less = 0.0; greatly = 0.0; //輸入 for (int i=0; i<nStudents; i++) { cin >> everyStudentCost[i]; } //求總花費 for (int i=0; i<nStudents; i++) { totalCost += everyStudentCost[i]; } //求平均值 average = totalCost / nStudents; //求less和greatly的值 for (int i=0; i<nStudents; i++) { if (everyStudentCost[i] < average) { //精度處理,保留兩位小數。先乘以100取其整數部分,然後再除以100.00 less += ((int)(100*(average - everyStudentCost[i])) / 100.00); } else { greatly += ((int)(100*(everyStudentCost[i] - average)) / 100.00); } } //求出less和greatly中的最小值 if (less > greatly) { cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "$" << less << endl; } else { cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "$" << greatly << endl; } } return 0;}