从长度为n的序列中找出平均值最大的长度不小于L的连续序列

/*
* @Author: hzf
* @Date:   2020-02-24 11:22:45
* @Last Modified by:   hzf
* @Last Modified time: 2020-02-24 11:46:15
*/
#include <stdio.h>

float GetAverage_MaxLength(int *a, int n, int l)//*a表示原序列,n表示序列长度,l表示子序列最小长度
{
	int res = 0;//临时结果初始化为0
	float result = 0.0;
	if(n < l)
		return 0;
	for (int length = l; length < n; ++length)//子序列的长度从l到n
	{
		int total = 0;
		for(int i=0; i<length; i++)
			total += a[i];//先获取前length个数字的平均值作为临时结果
		res = total/length;

		total = 0;//length个元素之和更新为0
		int i=0;//每次序列长度更新后都从首元素0开始,尾元素都从length开始
		for(int j=length; j<n; j++)
		{
			total = total + a[j] - a[i++];//新得序列的总和为原序列之和 + 新序列的末尾值 - 原序列的首元素
			result = total/length > res ? total/length : res;//更新result
		}
	}

	return result;
}
发布了31 篇原创文章 · 获赞 43 · 访问量 5225

猜你喜欢

转载自blog.csdn.net/qq_41582910/article/details/104474662
今日推荐