회원별 몸무게와 이름, 회원번호를 저장하고 평균값과 최대값 구하기. 회원수는 제한 없음.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int num;
char name[20];
double weight;
}Fitness;
double averageWeight(Fitness *pstList, int cnt);
int maxWeight(Fitness *pstList, int cnt);
void printInfo(Fitness *pstList, int mc);
void freeAty(Fitness *pstList, int cnt);
int main(void)
{
int nSize = 2;
static int sNIndex = 0;
int nMaxCount = 0;
double avg;
Fitness stListTemp; //임시list
Fitness* pstList; //동적할당 받을 list
pstList = (Fitness*)malloc(sizeof(Fitness)*nSize);
do
{
if(sNIndex >= nSize)
{
nSize = nSize + 2;
pstList = (Fitness*)realloc(pstList,nSize*sizeof(Fitness));
}
else
{
printf("User Number : %d\n",sNIndex+1);
stListTemp.num = sNIndex;
fflush(stdin);
printf("User Name : ");
gets(stListTemp.name);
printf("enter the weight : ");
scanf("%lf",&(stListTemp.weight));
pstList[sNIndex] = stListTemp;
fflush(stdin);
sNIndex++;
printf("Anymore?(Y/N)");
}
}while(getchar() != 'N');
printf("#total user : %d\n",sNIndex);
avg = averageWeight(pstList,sNIndex);
printf("#average of weight : %.2f\n",avg);
printf("the best pig!! : \n");
nMaxCount = maxWeight(pstList,sNIndex);
printInfo(pstList,nMaxCount);
return 0;
}
double averageWeight(Fitness *pstList, int cnt)
{
int i;
double total_weight = 0.0;
for(i=0;i<=cnt;i++)
{
total_weight = total_weight + pstList[i].weight;
//무게 총합 확인. 확인후 지우기
}
printf("total_weight : %.2f \n",total_weight);
return total_weight / cnt;
}
int maxWeight(Fitness *pstList, int cnt)
{
int i;
int k = 0;
double max = pstList[0].weight; //최대값 초기화
for(i=1;i<cnt;i++)
{
if(max < pstList[i].weight)
{
max = pstList[i].weight;
k = i;
}
}
return k;
}
void printInfo(Fitness *pstList, int nMaxCount)
{
printf("Number : %d\n",pstList[nMaxCount].num);
printf("Name : %s\n",pstList[nMaxCount].name);
printf("Weight : %.2lf\n",pstList[nMaxCount].weight);
}
void freeAty(Fitness *pstList, int sNIndex)
{
int i;
for(i=0;i<sNIndex;i++)
{
free(pstList);
}
}
댓글 없음:
댓글 쓰기