C 语言双向 ave、C 语言实验 7:函数程序设计-2
【选做题】设全社会共有n人,设计函数计算相对贫困率。要求:每人的可分配所得从键盘输入。输入输出均在主调函数内实现。
#define _CRT_SECURE_NO_DEPRECATE
#include
#include
int datalen = 0;
struct students
{
double mark;
struct students *next;
};
struct students *len()
{
struct students *p,*q,*header;
double sck;
header = p = (struct students *)malloc(sizeof(struct
students));
printf("请输入成绩,输入0结束输入\n");
scanf("%lf", &sck);
while (sck!=0)
{
q = (struct students *)malloc(sizeof(struct
students));//为q分配新的内存
q->mark = sck;
p->next = q;
p = q;
scanf("%lf", &sck);
}
p->next = NULL;
return header;
}
//求和
double fun(struct students *h)
{
struct students *p = h->next;
double ave = 0;
int j = 0, i = 0;
while (p != NULL)
{
datalen++;
ave += p->mark;
p = p->next;
}
return ave;
}
//排序
void Sort(struct students *h)
{
struct students *p,*q;
double count;
q = h->next;
p = h->next->next;
for (int a = 0; a < datalen; a++)
{
while (p != NULL)
{
if ((q->mark)
>(p->mark))
{
count = q->mark;
q->mark = p->mark;
p->mark = count;
}
p = p->next;
}
}
}
//求中位数
double Median(struct students *h)
{
struct students *p = h->next;
int j = 0, i = 0;
double count;
if (datalen % 2 == 0)
j = 0;
else
j = 1;
if (!j)
{
i = 0;
while (((datalen - 1) - 2 * i) == 0)
i++;
p = h->next;
for (int a = 0; a < i; a++)
if (p != NULL)
p = p->next;
count = p->mark;
p = h->next;
for (int a = 0; a < (datalen - 1 - i); a++)
if (p != NULL)
p = p->next;
count = count + p->mark;
return (1.0*count / 2);
}
if (j)
{
i = (datalen - 1) / 2;
p = h->next;
for (int a = 0; a < i; a++)
{
if (p != NULL)
{
p = p->next;
}
}
return p->mark;
}
return 1;
}
int main(void)
{
struct students *c, *p;
double ave;
int count = 0;
c = len();
fun(c);
Sort(c);
ave = Median(c);
p = c->next;
while (p != NULL)
{
if ((p->mark) < ave)
count++;
p = p->next;
}
ave = 1.0*count / datalen;
printf("%.2lf%%", ave * 100);
return 0;
}
刚学链表,操作笨拙,勿喷。