2024-11-27 06:48:51
说明:
1.用户不需要事先指定需要输入多少个数
做法:while(scanf("%lf",&data)){},这样当scanf函数试图从用户输入中读取一个浮点型数值失败的时候 不再继续读取,!!!好处:可以输入多行数据,以任意字母结束
2.将所有的数存储到动态分配的内存中
做法:使用链表来存储就行了,记住!!:一定要记得释放内存
使用示例:
Please Input Some Float Values:
1.1 2.2 3.3
4.4 5.5 6 7 8 9
4.1 a
Data In List Are:
1.100000 2.200000 3.300000 4.400000 5.500000 6.000000 7.000000 8.000000 9.000000 4.100000
Average=5.060000
Press any key to continue
说明:当scanf("%lf",&data))函数读取到4.1后面的"a"时,判断得出该输入不是一个浮点数,从而中断读取操作。
#include <stdio.h>
#include <malloc.h>
struct ListNode
{
ListNode* next;
double data;
};
ListNode* Append(ListNode *pList,double data)
{
ListNode *pNew = (ListNode*)malloc(sizeof(ListNode));
pNew->data = data;
pNew->next = NULL;
if (!pList)
{
pList = pNew;
pList->next = NULL;
}
else
{
ListNode *pLast = pList;
while(pLast->next)
{
pLast = pLast->next;
}
pLast->next = pNew;
}
return pList;
}
double Average(ListNode *pList)
{
printf("Data In List Are:\n");
int i=0;
double dSum=0;
ListNode *pNode = pList;
while(pNode)
{
dSum+=pNode->data;
printf("%f ",pNode->data);
pNode=pNode->next;
i++;
}
return (dSum/i);
}
void Free(ListNode *pList)
{
ListNode *pNext,*pNode = pList;
while(pNode)
{
pNext=pNode->next;
free(pNode);
pNode=pNext;
}
}
void main()
{
double data,aver=0;
ListNode *pList=NULL;
printf("Please Input Some Float Values:\n");
while(scanf("%lf",&data))
{
pList = Append(pList,data);
}
aver = Average(pList);
printf("\nAverage=%f\n",aver);
Free(pList);
}
2024-11-27 06:23:58
2024-11-27 07:08:11
2024-11-27 06:36:19