簡體   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