我有一個數據源。它每分鐘給出一個數字。我想計算最後100個數字的平均值。我如何用C來做到這一點?如何計算數量不斷增加的最後100位數的數量池
例如,輸入是1,2,3,4, ... 150
,那麼我想要得到的平均值爲50 . . . 150
。
一分鐘後,號碼池更改爲1,2,3,4.....150,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",¤t->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;
}
這些值是否在數組中? – Chinna
將第一個數字從總和中除去,將新數字加到總和中,再除以100。 –
我不在乎數據的來源,我只是使用scanf來模擬數據。 – Simon