n定義一個結構用來放全班個人成績
uenglish: int
uprogram: int
umath: int
uaverage: float
n首先輸入一個int 代表要放多少人的成績(>=4)
nmain()用 new 配置成績結構空間
n將該結構空間傳給一function 做輸入(scanf) (Call by address)
n將該結構空間傳給一function 做輸出(Call by value/address)
n將該結構空間傳給一function 算全班各科平均(Call by address)
n最後, 不用時要delete 該結構空間
#include <stdio.h>
#include <stdlib.h>
struct score
{
int id,english,program,math;
float avgerage;
};
typedef struct score SCORE;
void input_data(SCORE *data, int size);
void average(SCORE *data, float *avg_eng, float *avg_pro, float *avg_mat, float *avg_avg, int size);
void printdata(SCORE *data, int size);
void main(void)
{
int people;
float avg_eng,avg_pro,avg_mat,avg_avg;
SCORE *data_array;
printf("Please enter the number of people >");
scanf("%d",&people);
data_array = new SCORE[people];
input_data(data_array,people);
average(data_array,&avg_eng,&avg_pro,&avg_mat,&avg_avg,people);
printdata(data_array,people);
printf("Avg\t%.2f\t%.2f\t%.2f\t%.2f\n",avg_eng,avg_pro,avg_mat,avg_avg);
delete [] data_array;
system("pause");
}
void input_data(SCORE *data, int size)
{
for(int i=0;i<size;i++)
{
(*(data+i)).id=i+1;
printf("Input %d-th score\n",i+1);
printf("\tEnglish >");
scanf("%d",&((data+i)->english));
printf("\tProgram >");
scanf("%d",&((data+i)->program));
printf("\tMath >");
scanf("%d",&((data+i)->math));
(*(data+i)).avgerage=((*(data+i)).english+(*(data+i)).program+(*(data+i)).math)/3.0;
}
}
void average(SCORE *data, float *avg_eng, float *avg_pro, float *avg_mat, float *avg_avg, int size)
{
int total_eng=0,total_pro=0,total_mat=0;
float total_avg=0;
for(int i=0;i<size;i++)
{
total_eng=total_eng+(*(data+i)).english;
total_pro=total_pro+(*(data+i)).program;
total_mat=total_mat+(*(data+i)).math;
total_avg=total_avg+(*(data+i)).avgerage;
}
*avg_eng=total_eng/(float)size;
*avg_pro=total_pro/(float)size;
*avg_mat=total_mat/(float)size;
*avg_avg=total_avg/(float)size;
}
void printdata(SCORE *data, int size)
{
printf("ID\tEnglish\tProgram\tMath\tAvgerage\n");
for(int i=0;i<size;i++)
printf("%d\t%d\t%d\t%d\t%.2f\n",(*(data+i)).id,(*(data+i)).english,(*(data+i)).program,(*(data+i)).math,(*(data+i)).avgerage);
}
沒有留言:
張貼留言