Given a sequence of N integers, calculate the average of this sequence, rounded to the second decimal place.
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
The first line of the input represents the number of test cases. Starting from the second line, each line represents a test case. Each test case consists of: 1. An integer N, which is the length of the sequence (ranging from 1 to 100). 2. The next N integers, which are the elements of the sequence (each ranging from -10000 to 10000). For each test case, calculate the average of the sequence, rounded to two decimal places. | For each test case, output the average value on a new line, rounded to two decimal places. |
2 5 2 4 6 8 10 3 52 30 61 | 6.00 47.67 |
Thought Process
Use a For loop to add all the numbers to a variable, then store the value of sum/N in a double variable. It is important to note that both variables sum and N can be declared using double to avoid type conversion when calculating the average. After calculation, use printf(%.2f\n, ans) to round the result to two decimal places for output.
Sample Code-ZeroJudge D786: Average
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
int N;
cin >> N;
for (int i = 0; i<N; i++)
{
double M;
cin >> M;
double sum = 0;
for (int j = 0; j<M; j++)
{
double tmp;
cin >> tmp;
sum += tmp;
}
double ans = sum/M;
printf("%.2f\n", ans);
}
}
//ZeroJudge D786
//Dr. SeanXD