匿名用户
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;
}