AVGNUMBS - Editorial

PROBLEM LINK

Practice
DeCode 2021 - 2 seconds left

Author: akcube, fangahawk
Tester: Announcement
Editorialist: akcube

DIFFICULTY

CAKEWALK

PROBLEM

Given a set of N numbers, output their average. Find the bug in the code.

BUGGY CODE

#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    int n;
    cin >> n;

    int sum = 0;
    for(int i = 0; i < n; i++) {
        int x;
        cin >> x;
        sum += x;
    }
    double ans = sum / n;
    cout << fixed << setprecision(9) << ans << endl;
}

QUICK EXPLANATION

The buggy code performs integer division, giving WA.

EXPLANATION

The problem asks to output the average of N integers. The bug is that the code performs integer division on the sum of the N integers which takes the floor of the division before assigning it to the double variable. This gives WA. The intended solution is to input any set of N numbers (within constraints) whose sum is not divisible by N. More formally,

N
a_1, a_2, \dots, a_N

Such that (\sum_{i=1}^{N} a_i) \ mod \ N \neq 0

An example of such a test case:

3
2 3 5