java链表求平均值和方差_用c语言链表求n个数的均值和标准差

这篇博客介绍如何使用C语言实现链表数据结构,并通过链表计算一组数值的平均值和标准差。博主首先建立了数学模型,然后定义了链表结构体,接着实现了一系列链表操作函数,包括获取链表长度、计算平均值、计算标准方差、插入节点和打印链表。最后,博主给出了一个示例程序,用于输入数值并输出链表的长度、平均值和标准差。
摘要由CSDN通过智能技术生成

匿名用户

1级

2015-06-15 回答

//解决问题的思路

//1. 建立数学模型

//    均值avg = (a1+a2+...an)/n

//    标准差sd^2 = [(a1-avg)^2 + (a2-ave)^2+...+(an-avg)^2)] / n

//2. 定义结构体

//3. 建立和初始化链表

//4. 编写对于对象的各个函数

//    listlen()返回当前链表中元素是多少个

//    listavg()返回当前链表中元素的平均值

//    stdeva()返回当前链表的标准方差

//    push()将节点node加入链表头

//    print()打印当前链表内的所有值

#include 

#include 

#include 

typedef struct node * Node;

typedef struct node * List;

struct node

{

double value;

Node next;

};

int listlen(List list)

{

int len = 0;

for( list = list -> next; list != NULL; list = list -> next)

len++;

return len;

}

double listavg(List list)

{

double sum = 0;

Node curr = list;

for (curr = curr ->next; curr != NULL; curr = curr -> next )

sum += curr->value;

return (sum / (double)listlen(list));

}

double stdeva(List list)

{

double stdeva = 0;

double avg = listavg(list);

Node curr = list;

for (curr = curr->next; curr != NULL; curr = curr ->next)

stdeva += (curr -> value - avg) * (curr -> value - avg);

stdeva = sqrt(stdeva / listlen(list));

return stdeva;

}

void push(List list, Node node)

{

node->next = list->next;

list->next = node;

}

void print(List list)

{

for (list = list -> next; list != NULL; list = list ->next )

printf("%lf\n", list->value );

}

int main()

{

List list;

list = (List)malloc(sizeof(List));

// init list

// dummy head, null tail

list->next = NULL;

//input value into the list;

int n;

int i;

double temp;

printf("Pls input the n first:\n");

scanf("%d", &n);

printf("Pls input %d numbers\n",n);

for(i = 0; i 

{

scanf("%lf",&temp);

//create new node;

Node new;

new = (Node)malloc(sizeof(Node));

if(new == NULL)

printf("Fail to locate storage!\n");

new -> value = temp;

push(list, new);

}

//output

print(list);

printf("List length is %d\n", listlen(list));

printf("The average is %lf.\n", listavg(list));

printf("The SD is %lf.\n",stdeva(list));

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值