好久没时间学c语言了,最近重新捡起来,之前这道题卡了很久,可能是我没读懂题,这次回来几分钟就搞定了。果然学习还是要持续,不然卡在哪里都不记得,起不到总结经验的效果了。希望看到的朋友能引以为戒,保持学习的习惯。
题目:
编写一个程序,提示用户输入3个数集,每个数集包括5个double值,实现一下功能:
a.储存二维数组
b.计算每个数集的平均值
c.计算所有数的平均数
d.找出最大值
e.打印结果
代码:
#include "stdio.h"
#define ROWS 3
#define COLS 5
double cal_avg_row(double ar[][COLS],int row);
double cal_avg_all(double ar[][COLS],int row);
double max_value(double ar[][COLS],int row);
int main(void){
printf("Please input 3 sets of numbers,which have 5 numbers in each set.\n");
int i,j;
double set1[COLS];
double set2[COLS];
double set3[COLS];
double allsum=0;
double maxvalue = 0;
double array[ROWS][COLS];
double avg_row[ROWS];
printf("the first set:");
for (i=0; i<COLS; i++) {
scanf("%lf",&set1[i]);
}
printf("the second set:");
for (i=0; i<COLS; i++) {
scanf("%lf",&set2[i]);
}
printf("the third set:");
for (i=0; i<COLS; i++) {
scanf("%lf",&set3[i]);
}
printf("a.将输入的三个数集储存为二维数组\n");
printf("b.计算所有数值的平均数\n");
printf("c.找出所有数值的最大值\n");
printf("d.打印出结果\n");
printf("请输入要实现的功能:\n");
char func;
while (scanf("%s",&func) != EOF) {
if(func >= 'a' && func <= 'e'){
switch (func) {
case 'a':
for(i=0 ; i<COLS ; i++){
array[0][i] = set1[i];
}
for(i=0 ; i<COLS ; i++){
array[1][i] = set2[i];
}
for(i=0 ; i<COLS ; i++){
array[2][i] = set3[i];
}
printf("save done.\n");
break;
case 'b':
for(i=0;i<ROWS;i++){
avg_row[i] = cal_avg_row(array, i);
}
printf("calculate done.\n");
break;
case 'c':
allsum =cal_avg_all(array, ROWS);
printf("calculate done.\n");
break;
case 'd':
maxvalue = max_value(array, ROWS);
printf("calculate done.\n");
break;
case 'e':
for(i=0;i<ROWS;i++){
printf("the average of the %d row is %.2lf.\n",i,avg_row[i]);
}
printf("the average of all numbers is %.2lf.\n",allsum);
printf("the max value is %.2lf.\n",maxvalue);
default:
printf("Done.");
break;
}
}
}
return 0;
}
double cal_avg_row(double ar[][COLS],int row){
int i;
double sum = 0;
double avg = 0;
for(i=0; i<COLS ;i++){
sum += ar[row][i];
}
avg = sum/COLS;
return avg;
}
double cal_avg_all(double ar[][COLS],int row){
int i,j;
double allSum = 0 ;
double avg = 0;
for(i=0 ; i<row ; i++){
for(j=0 ; j<COLS ; j++)
allSum += ar[i][j];
}
avg = allSum/(COLS*row);
return avg;
}
double max_value(double ar[][COLS],int row){
int i,j;
double max = 0 ;
for(i=0 ; i<row ; i++){
for(j=0 ; j<COLS ; j++)
if(ar[i][j] > max)
max = ar[i][j];
}
return max;
}
运行结果:
Please input 3 sets of numbers,which have 5 numbers in each set.
the first set:1.1 2.1 3.1 4.1 5.1
the second set:2.1 3.1 4.1 5.1 6.1
the third set:3.1 4.1 5.1 6.1 7.1
a.将输入的三个数集储存为二维数组
b.计算所有数值的平均数
c.找出所有数值的最大值
d.打印出结果
请输入要实现的功能:
a
save done.
b
calculate done.
c
calculate done.
d
calculate done.
e
the average of the 0 row is 3.10.
the average of the 1 row is 4.10.
the average of the 2 row is 5.10.
the average of all numbers is 4.10.
the max value is 7.10.
Done.