#C14477. Calculate Average Grades
Calculate Average Grades
Calculate Average Grades
Given a list of student records, each record is a JSON object that may contain the keys name
(a string), age
(an integer), and an optional grades
array (a list of integers). Your task is to compute the average grade for each student. The average should be calculated using the formula:
\(\text{average} = \frac{\sum_{i=1}^{n} g_i}{n}\)
round the result to two decimal places. If a student has no grades
key or has an empty array, then the average is defined to be 0.
The modified records should include a new key average
for each student. The input and output for this problem are provided in JSON format via standard input and output respectively.
inputFormat
The input consists of a single JSON array provided from standard input (stdin). Each element of the array is a JSON object representing a student record. Each record contains the keys:
name
: a string indicating the student's nameage
: an integer indicating the student's agegrades
(optional): an array of integers representing the student's grades
outputFormat
Print to standard output (stdout) a JSON array of student records. Each record should be the same as the input record but with an additional key average
whose value is the average of the grades (rounded to two decimal places). For records without grades, output average
as 0.
[{"name":"Alice","age":20,"grades":[90,85,88]},{"name":"Bob","age":22,"grades":[78,82]},{"name":"Charlie","age":23,"grades":[]}]
[{"name":"Alice","age":20,"grades":[90,85,88],"average":87.67},{"name":"Bob","age":22,"grades":[78,82],"average":80.0},{"name":"Charlie","age":23,"grades":[],"average":0}]