一维数组
读入一个一维数组,并求出平均值。
#include<stdio.h>
int main()
{
int i, n;
float average, totalscore = 0;
//将int score[n]放在这程序运行不出来
printf("Please enter a number:");
scanf("%d", &n);
//读入数组
int score[n];
printf("Please enter numbers:");
for(i = 0; i < n; i++)
{
scanf("%d", &score[i]);
totalscore += score[i];
}
average = totalscore/n;
printf("average = %f", average);
return 0;
}
二维数组
<平年,闰年>
#include<stdio.h>
#define MONTHS 12 //宏定义
int main()
{
int month, year;
int days[2][MONTHS] = {{31,28,31,30,31,30,31,31,30,31,30,31},
{31,29,31,30,31,30,31,31,30,31,30,31}};
do{
printf("Please enter year, month:");
scanf("%d,%d", &year,&month);
}while(month<1||month>12); //处理不合法数据的输入
if(((year%4 == 0) && (year%100 != 0) ) || (year%400 == 0) ) //闰年
printf("The number of days is %d", days[1][month-1]);
else
printf("The number of days is %d", days[0][month-1]);
return 0;
}
向函数传递数组
向函数传递一维数组<输入成绩,求平均分>
#include<stdio.h>
#define N 40 //宏定义,数组中可以输入40个元素
void ReadScore(int score[], int n); //int ReadScore()也可以
float AverScore(int score[], int n); //函数声明一定不要写在main函数里面
int main()
{
int n;
int score[N]; //声明时填入N
float aver;
printf("please enter the number of class:"); // n<=N,即<40
scanf("%d", &n);
ReadScore(score, n);
aver = AverScore(score, n); //调用函数中只写数组名
printf("The average score is %f", aver);
return 0;
}
//输入成绩
void ReadScore(int score[], int n)
{
int i;
printf("Please enter score:");
for(i = 0; i < n; i++)
{
scanf("%d", &score[i]);
}
}
//求平均分
float AverScore(int score[], int n)
{
int i;
float average,sum;
for(i = 0; i < n; i++)
{
sum += score[i];
}
average = sum/n;
return average;
}
当输入成绩为负时,表示输入结束,并输出平均分和输入的学生人数
#include<stdio.h>
#define N 40
//ReadScore函数变化,声明变化
int ReadScore(int score[]);
float AverScore(int score[], int n);
int main()
{
int n, score[N];
float average;
n = ReadScore(score);
printf("The number of total students is %d\n", n); //ReadScoer函数返回输入学生的人数
average = AverScore(score, n);
printf("The average of score is %f", average);
return 0;
}
int ReadScore(int score[])
{
int i = -1; // i 的初始值 -1,保证循环体内 i 增 1 后,数组下标从 0 开始
do{
i++;
printf("Please enter score:"); //printf函数放在do循环外,程序不能正常运行
scanf("%d", &score[i]);
}while(score[i]>0);
//数组中元素的个数应该是 1+1 个,但最后一个 <0 作为结束的标记值,不算入学生成绩
return i;
}
float AverScore(int score[], int n)
{
int i;
float sum = 0,aver;
for(i =0; i < n; i++)
{
sum += score[i];
}
aver = sum/n;
return aver;
}
输入成绩,为负结束,打印最高分
#include<stdio.h>
#define N 40
int ReadScore(int score[]);
int FindMax(int score[], int n);
int main()
{
int n, score[N], max;
n = ReadScore(score);
printf("The number of total students is %d\n", n);
max = FindMax(score, n);
printf("The highest score is %d\n", max);
return 0;
}
int ReadScore(int score[])
{
int i = -1;
do{
i++;
printf("Please enter score:");
scanf("%d", &score[i]);
}while(score[i]>0);
return i;
}
//找出最高分
int FindMax(int score[], int n)
{
int max,i;
max = score[0];
for(i = 1; i < n; i++)
{
if(score[i] > max);
max = score[i];
}
return max;
}