C primer plus
第10章
第13题:
#include <stdio.h>
void get_arr(double ar[][5]);
void get_aver(double ar[][5]);
void get_avet(double ar[][5]);
void get_max(double ar[][5]);
int main(void) {
double list[3][5];
get_arr(list);
get_aver(list);
get_avet(list);
get_max(list);
return 0;
}
void get_arr(double ar[][5]) {
double a;
int i=0,j=0;
printf("Please enter 5 numbers:\n");
while (i !=3 && scanf("%lf", &a) == 1) {
ar[i][j++] = a;
if (j == 5 ) {
j = 0;
i++;
printf("Next enter:"); #注:这个Next enter 会多打印一次,换成for循环应该可以解决 但不影响结果,暂时就这样了
}
}
printf("Now the array is:\n");
for (i = 0; i < 3; i++) {
putchar('\n');
for (j = 0; j < 5; j++) {
printf("%g ", ar[i][j]);
}
}
}
void get_aver(double ar[][5]) {
int r;
int i = 0,j = 0;
double tot = 0;
double ave = 0;;
printf("Please choose the row you want to count:");
while (scanf("%d", &r) == 1) {
switch (r) {
case 1:
i = 0;
for (j = 0; j < 5; j++) {
tot += ar[i][j];
}
ave = tot / 5;
printf("The average number for the %d row is %g\n", i + 1, ave);
tot = 0;
printf("Enter again(q to quit):");
break;
case 2:
i = 1;
for (j = 0; j < 5; j++) {
tot += ar[i][j];
}
ave = tot / 5;
printf("The average number for the %d row is %g\n", i + 1, ave);
tot = 0;
printf("Enter again(q to quit):");
break;
case 3:
i = 2;
for (j = 0; j < 5; j++) {
tot += ar[i][j];
}
ave = tot / 5;
printf("The average number for the %d row is %g\n", i + 1, ave);
tot = 0;
printf("Enter again(q to quit):");
break;
default:
printf("Enter a number between 1~3:");
break;
}
}
}
void get_avet(double ar[][5]) {
int i, j;
double tot = 0;
double ave = 0;
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++) {
tot += ar[i][j];
}
}
ave = tot / 15;
printf("The average number for the whole array is %g\n", ave);
}
void get_max(double ar[][5]) {
double max;
int i, j;
max = ar[0][0];
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++) {
if (max < ar[i][j])
max = ar[i][j];
}
}
printf("The max number in this array is %g", max);
}