#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_SIZE 256
typedef struct tag_StudentData
{
double height;
double weight;
struct tag_StudentData *next;
} StudentData;
StudentData StudentDataRoot = { 0, 0, NULL};
double InputNumber(const char *prompt)
{
char buf[BUF_SIZE];
double ret;
for(; ; )
{
printf("%sを入力してください: ", prompt);
if(fgets(buf, sizeof(buf), stdin) == NULL)
return -1;
else if(sscanf(buf, "%lf", &ret) == 1)
break;
puts("数字で入力してください");
}
return ret;
}
void InputStudentData()
{
StudentData *sd = &StudentDataRoot;
while(sd->next != NULL)
sd = sd->next;
if((sd->next = (StudentData *)malloc(sizeof(StudentData))) == NULL)
{
perror("メモリが足りません");
return;
}
sd = sd->next;
sd->height = InputNumber("身長");
sd->weight = InputNumber("体重");
sd->next = NULL;
}
void PrintAverageHeight()
{
int Count = 0;
double TotalHeight = 0;
StudentData *sd = &StudentDataRoot;
while(sd->next != NULL)
{
sd = sd->next;
++Count;
TotalHeight += sd->height;
}
if(Count < 1)
puts("データがありません");
else
printf("平均身長=%.1f\n", TotalHeight / Count);
}
void PrintAverageWeight()
{
int Count = 0;
double TotalWeight = 0;
StudentData *sd = &StudentDataRoot;
while(sd->next != NULL)
{
sd = sd->next;
++Count;
TotalWeight += sd->weight;
}
if(Count < 1)
puts("データがありません");
else
printf("平均体重=%.1f\n", TotalWeight / Count);
}
void PrintAllData()
{
StudentData *sd = &StudentDataRoot;
if(sd->next == NULL)
{
puts("データがありません");
return;
}
puts("身長 体重");
while((sd = sd->next) != NULL)
printf("%5.1f %5.1f\n", sd->height, sd->weight);
}
void DeleteAllData(StudentData *sd)
{
if(sd == NULL)
return;
DeleteAllData(sd->next);
free(sd);
}
int main(void)
{
for(; ; )
{
int innum;
puts(
"\n"
"1: 生徒データの入力\n"
"2: 平均身長の表示\n"
"3: 平均体重の表示\n"
"4: データ表の表示\n"
"5: データの全消去\n"
"\n"
"0: プログラムの終了\n"
);
innum = (int)InputNumber("番号");
if(innum < 0)
goto ClearData;
switch(innum)
{
case 1:
InputStudentData();
break;
case 2:
PrintAverageHeight();
break;
case 3:
PrintAverageWeight();
break;
case 4:
PrintAllData();
break;
case 5:
DeleteAllData(StudentDataRoot.next);
StudentDataRoot.next = NULL;
break;
case 0:
goto ClearData;
}
}
ClearData:
DeleteAllData(StudentDataRoot.next);
return 0;
}