c++ - 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
解决方案
您正在尝试访问该行中超出数组范围的元素
avg=(a[n]+a[n-1]+a[n-2])/3.;
尝试使用
avg = (a[n-1]+a[n-2]+a[n-3])/3.;
并且还要确保'n'的值不会大于 10,因为你的数组大小是 10。
推荐阅读
- machine-learning - 利用强化学习中学到的策略的方法
- python - 我如何组织 SQLAlchemy 关系以便像 JSON 一样的 dict 访问?
- ios - 尝试制作一个相机应用程序,对 Swift 来说是新的
- solr - SolrJ addFilterQuery 被忽略
- python-3.x - 以列表格式获取 KMeans 之后的聚类点
- sql - 如何通过 sql 数据库中的自定义 id 获取特定产品和组的最大计数
- angular - 设置可通过 ActivatedRoute 检索的特定路由参数
- c# - Entity Framework Core 2.0 将枚举映射到 SQL Server 中的 tinyint 在查询时引发异常
- php - 查询不工作。在 Laravel 中找不到页面
- sql - 分解表以在列中进行透视(SQL,PYSPARK)