The Problem
It is said that 90% of frosh expect to be above average in their class. You are to provide a reality check.
Input
The first line of standard input contains an integer C, the number of test cases. C data sets follow. Each data set begins with an integer, N, the number of people in the class (1 <= N <= 1000). N integers follow, separated by spaces or newlines, each giving the final grade (an integer between 0 and 100) of a student in the class.
Output
For each case you are to output a line giving the percentage of students whose grade is above average, rounded to 3 decimal places.
Sample Input
5
5 50 50 70 80 100
7 100 95 90 80 70 60 50
3 70 90 80
3 70 90 81
9 100 99 98 97 96 95 94 93 91
Sample Output
40.000%
57.143%
33.333%
66.667%
55.556%
解題思考
這一題只是給與一定數量的「分數」,要求你計算出比全體平均分數高的百分率而已。
首先,我們在輸入的分數的同時,計算出總分之後,就是要計算比平均高的人數。
為求精準,我是將每個人的分數乘以人數再與總分比較,而不是先由總分求出平均分數再跟每個人的分數比較。
最後,根據人數求出百分率。完成!
參考解答(C++)
#include <iostream> #include <iomanip> using namespace std; int main(void) { int c; cin >> c; // 設定顯示至小數點第三位 cout << setiosflags(ios::fixed) << setprecision(3); for (int i = 0; i < c; i++) { int n, *score, total = 0; cin >> n; // 輸入分數, 並計算總和 score = new int[n]; for (int j = 0; j < n; j++) { cin >> score[j]; total += score[j]; } // 得到有多少人比平均高分 int man = 0; for (int j = 0; j < n; j++) { if (score[j] * n > total) { man++; } } cout << (((double)man * 100) / n) << "%" << endl; delete [] score; } #ifndef ONLINE_JUDGE system("pause"); #endif }
0 回覆:
張貼留言