加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

结构体 及 函数的调用

(2007-04-05 17:01:17)
分类: C语言

#include<stdio.h>
#include<string.h> //strcpy(目标,源)

//自定义结构体,相当与Java中定义一个类
struct Student
{
 int id;
 char name[20];
 float score;
 int group;
};
//自定义函数pt(数组,数组长度)用来打印Student类型数组中 所有记录
void pt(struct Student stu[],int len)
{
 int i;
 printf("学号\t姓名\t\t成绩\t组号\n");
 for(i = 0 ; i < len ; i++)
 {
  printf("%d\t",stu[i].id);
  printf("%s\t",stu[i].name);
  printf("%.1f\t",stu[i].score);
  printf("%d\t\n",stu[i].group);
 }
 printf("------------------------------------------------------\n");
}
//自定义函数search(数组,数组长度,所要查询的id)
void search(struct Student stu[],int len,int id)
{
 int i;
 for(i = 0 ; i < len ; i++)
 {
  if(stu[i].id == id)
  {
   printf("%d\t",stu[i].id);
   printf("%s\t",stu[i].name);
   printf("%.1f\t",stu[i].score);
   printf("%d\t\n",stu[i].group);
  }
 }
 printf("------------------------------------------------------\n");
}
//自定义函数jiafen(数组,数组长度,加分条件,所要加的分值)
void jiafen(struct Student stu[],int len,float score,float add)
{
 int i;
 for(i = 0 ; i < len ; i++)
 {
  if(stu[i].score > score)
  {
   stu[i].score += add;
  }
 }
}
//自定义函数avgScore(数组,数组长度)用来求出所有记录score的总和
float avgScore(struct Student stu[],int len)
{
 int i;
 float sum = 0,avg;
 for(i = 0 ; i < len ; i++)
 {
  sum = sum + stu[i].score;
 }
 avg = sum / 5;
 return avg;
}
void main()
{
 struct Student stu[5]; //C中 用自定义结构体 来定义变量或数组  要在前面加struct  C++中可不写
 float avg;

 //插入5条记录
 stu[0].id = 1;
 strcpy(stu[0].name,"changming");
 stu[0].score = 97.5f;
 stu[0].group = 1;

 stu[1].id = 2;
 strcpy(stu[1].name,"zhangdepei");
 stu[1].score = 68.5f;
 stu[1].group = 1;

 stu[2].id = 3;
 strcpy(stu[2].name,"lihongzhi");
 stu[2].score = 78.0f;
 stu[2].group = 2;

 stu[3].id = 4;
 strcpy(stu[3].name,"luojiaying");
 stu[3].score = 70.0f;
 stu[3].group = 3;

 stu[4].id = 5;
 strcpy(stu[4].name,"zhoujielun");
 stu[4].score = 66.5f;
 stu[4].group = 3;

 //打印所有学生信息
 pt(stu,5);

 //打印id为2的学生信息
 search(stu,5,2);

 //把所有成绩大于70分的学生成绩+5
 jiafen(stu,5,70,5);
 pt(stu,5);

 //avg分
 avg = avgScore(stu,5);
 printf("%.2f\n",avg);
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有