首页 > 解决方案 > Finding an average of last 3 numbers of array

问题描述

I need to find an average of last three array's numbers. I tried using this code but something seems to be wrong.

#include <iostream>
#include <iomanip>
#include <algorithm>

using namespace std;

int main()
{
    int a[10];
    int n, sum = 0, kiek = 0;
    double avg;
    cin >> n;
    for(int i=0; i < n; i++)
    {
        cin >> a[i];
        sum = sum + a[i];
        kiek++;
    }
    avg = (a[n] + a[n-1] + a[n-2]) / 3.;
    cout << fixed << setprecision(3) << avg;
    return 0;
}

This is the input:

5

1 2 3 4 5

This is the output I get:

3.000

This is the output I want:

4.000

标签: c++

解决方案


您正在尝试访问该行中超出数组范围的元素

avg=(a[n]+a[n-1]+a[n-2])/3.;

尝试使用 avg = (a[n-1]+a[n-2]+a[n-3])/3.;

并且还要确保'n'的值不会大于 10,因为你的数组大小是 10。


推荐阅读