第61课 数组函数参数
·数组作为函数实参时,只传递数组的地址(首地址),并不传动整个数组的空间
·double scores[](定义函数时)
·double *score也可以(定义函数时)
·当用数组名作为实参调用函数时,数组首地址指针就被传递到函数中。
·学生成绩管理系统
//学生成绩管理系统*********************************************
#include <stdio.h>
#include <stdlib.h>
#define N 5
//书写一个小型的学生成绩管理系统
void input(double[]);//返回值不能是数组,录入函数
void sort(double[]);//给定一个数组,进行排序
void show(double[]);//给定一个数组,将结果打印出来
int main()
{
double scores[N];
//1、录入
input(scores); //输入函数,并将录入的score返回到主函数中来
printf("排序前\n");
show(scores);
//2、排序
sort (scores);
//3、按照某种格式打印
printf("排序后\n");
show(scores);
return 0;
}
void input(double scores[])
{
int i;
for(i = 0; i < N; i++)
{
printf("请输入第%d门课的成绩:", i + 1);
scanf("%lf",&scores[i]);
}
}
void sort(double scores[])
{
int i, j;
double temp;
for(i = 0; i < N - 1; i++)
{
for(j = i; j < N - i -1; j++)
{
if(scores[j] > scores[j+1])
{
temp = scores[j];
scores[j] = scores[j+1];
scores[j+1] = temp;
}
}
}
}
void show(double scores[])
{
int i;
printf("****************************************\n");
printf("语文\t数学\t英语\t物理\t化学\n");
for(i = 0; i < N; i++)
{
printf("%.2lf\t",scores[i]);
}
printf("\n****************************************\n");
}
//学生成绩管理系统*********************************************
/*注意:本程序有bug,最后排序虽然分数用冒泡排序结局了,但是show scores的时候,科目并没有进行排名,解决方案:建立char型二维数组来存储这几个变量*/
//运行结果*****************************************************
请输入第1门课的成绩:78
请输入第2门课的成绩:45
请输入第3门课的成绩:99
请输入第4门课的成绩:92
请输入第5门课的成绩:55
排序前
****************************************
语文 数学 英语 物理 化学
78.00 45.00 99.00 92.00 55.00
****************************************
排序后
****************************************
语文 数学 英语 物理 化学
45.00 78.00 55.00 92.00 99.00
****************************************
Process returned 0 (0x0) execution time : 15.742 s
Press any key to continue.
//运行结果*****************************************************
·查找下标
//*********************************************************程序
#include <stdio.h>
#include <stdlib.h>
#define N 5
//像传入的数组中查找num,如果存在,返回下标,不存在,返回-1
int find(double*,int );//返回值只有可能是-1或者下标,所以返回值是int型的,返回的数组名写不写都无所谓的
int main()
{
double scores[N] = {95,96,97,98,99};
double findNum;//要查找的数字
printf("请输入要查找的数字:\n");
scanf("%lf",&findNum);
printf("找到的数字下标为%d",find(scores,findNum));//在scores这个数组中查找findNum
return 0;
}
int find(double*scores,int findNum)
//函数声明的时候,参数确定类型就可以了,不必有数组名
//函数定义的时候,参数必须既有类型又有数值。
{
int findIndex = -1;//要查找的下标
int i;
for(i = 0; i < N; i++)
{
if(findNum == scores[i])
{
//记录下要查找的下标,结束查找动作
findIndex = i;
break;
}
}
return findIndex;
}
//*********************************************************程序
//*********************************************************运行结果
请输入要查找的数字:
99
找到的数字下标为4
Process returned 0 (0x0) execution time : 5.134 s
Press any key to continue.
//*********************************************************运行结果
Tips:量数组的大小
double test[] = {1,2,3,4,4,5,56,6,7,2};
printf("test数组的元素个数:%d\n",sizeof(test)/sizeof(test[0]));