繁体   English   中英

如何计算号码池数量增加的最后100个号码的平均值

[英]How to calculate the average of last 100 numbers of increasing quantity of numbers pool

我有一个数据源。 每分钟给出一个数字。 我想计算最近100个数字的平均值。 我该如何使用C?

例如,输入为1,2,3,4, ... 150那么我想获得平均值50 . . . 150 50 . . . 150 50 . . . 150

一分钟后,数字池更改为1,2,3,4.....150,151 ,那么我需要获取平均值51. . . 151 51. . . 151 51. . . 151 ,由于概念相同,请获取最后100个数字以计算平均值。

我尝试使用列表结构,首先获取所有数字的总和,然后从第一个数字减去总和以count-100来获取最后的100个数字。

这是我尝试过的代码:

#include <stdio.h>
#include <malloc.h>
#define N 5

int i,sum;

int main(void)
{
struct node //定义一个链表
{
    float num;  //链表的元素
    struct node *next;//下一个元素的指针
};
struct node *first=NULL;//第一个数据
struct node *current=NULL;//当前的数据
struct node *previous=NULL;//上一个数据

struct node *currentT=NULL;//
//    char temp='\0';

while (1==1)//循环输入数据,相当于每秒往链表中添加一个数据
{
    // printf("continue ?Y/N:  ");
    // scanf(" %c",&temp);

    // if (tolower(temp)=='n')
    //  break;
    current=(struct node*) malloc(sizeof(struct node));//获取链表的首地址
    if (first==NULL)//如果第一个数据为空就把当前的地址赋值给first
        first=current;
    if (previous!=NULL)//把当前的地址赋值给上一个数据的next指针
        previous->next=current;
    printf("please enter the num:");
    scanf("%f",&current->num);//输入数据
    current->next=NULL;//移动指针
    previous=current;

    currentT=first;//指针指向第一个数据
    float avg=0,sum=0,count=0;
    while (currentT!=NULL)//循环链表中所有的数据
    {
        printf("node's num is:%f \n",currentT->num);
        count=count+1;
        sum= sum+currentT->num;//求总和
        currentT=currentT->next;//指针下移

    }
    avg=sum/count;//求平均

    if(count>N)//如果链表长度大于N则减去链表前端的数据
    {
        currentT=first;//指针指向第一个数据
        int remove_count=0;
        while (currentT!=NULL)//循环链表中所有的数据
        {
            remove_count=remove_count+1;
            sum= sum-currentT->num;//求总和
            if(remove_count==count-N){//减到链表长度等于N时停止
                break;
            }
            currentT=currentT->next;//指针下移
        }
         avg=sum/N;//求平均
    }

    printf("sum is:%f \n",sum);

    printf("avg is:%f \n",avg);

}

return 0;
}

该算法似乎很简单。 保留排在最后的100个数字。 该队列将随时包含100个元素。 另外,您随时可以保留它们的和S。 当出现新号码时,请从队列中删除第一个号码,然后将新号码添加到队列中。 然后,只需减去第一个数字并添加新的数字,即可重新计算这100个数字的和S。

S = S - aOldFirst + aNewLast;

我将使用动态结构(例如,链表)来实现队列。

以下是使用数组的循环队列的实现,以及一个在添加新元素时返回元素平均值的函数。 队列已满时,该函数删除第一个元素。 因此,您只需为每个输入调用此函数,它将返回当前元素的平均值。

//declarations
#define MAXSIZE 5
int cq[MAXSIZE]={0};
int front=-1,rear=-1;
float AverageForNewElement(int);

//function definition 
float AverageForNewElement(int item)
{
    static int Sum=0;
    if(front ==(rear+1)%MAXSIZE)
    {
        if(front==rear)
            front=rear=-1;
        else
            front = (front+1)%MAXSIZE;
        Sum=Sum-cq[front];
    }
    if(front==-1)
        front=rear=0;
    else
        rear=(rear+1)%MAXSIZE;
    cq[rear]=item;
    Sum=Sum+cq[rear];
    return ((float)Sum/MAXSIZE);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM