代码:
#include <stdio.h>
#define YEARS 5
#define MONTHS 12
int main(void)
{
float rain_tot;
const float rain[YEARS][MONTHS]={
{4.3,4.3,4.3,3.2,2.0,2.0,1.2,0.5,3.5,4.3,5.3,5.6},
{8.5,8.2,1.2,1.6,2.4,0.0,0.2,0.9,0.3,1.4,5.2,7.3},
{9.1,8.5,6.7,4.3,2.1,0.8,0.2,0.2,1.1,2.3,6.1,8.4},
{7.2,9.9,8.4,3.3,1.2,0.8,0.4,0.2,0.0,0.6,1.7,4.3},
{7.6,5.6,3.8,2.8,3.8,0.2,0.0,0.0,1.3,1.7,2.6,5.2}
};
printf(" YEAR RAINFALL (inches):\n");
rain_tot=rain_year(rain,YEARS);
printf("The number returned from rain_tot() is %.1f.\n",rain_tot);
//年平均降水量
printf("The yearly average is %.1f inches.\n",rain_tot/YEARS);
//格式化输出每个月份的平均降水量的表头:
printf("The monthly averages are:\n");
printf("Yan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\n");
rain_month(rain,YEARS);//月平均降水量
return 0;
}
//这里需要返回数值的,使用float类型就会报错,为什么只能使用void类型?
void rain_year(float array[][MONTHS],int n)
{
int year,month;
float total,subtot;
//年降水总量
for(year=0,total=0;year<n;year++){
for(month=0,subtot=0;month<MONTHS;month++)
subtot+=*(*(array+year)+month);
printf("%5d\t%.1f\n",2000+year,subtot);
total+=subtot;
}
printf("The total rainfall is %.1f inches.\n",total);//这里的total值为200.1
return total;//这里的返回值怎么是36.0呢?
}
void rain_month(float array[][MONTHS],int n)
{
int year,month;
float subtot;
//月平均降水量
for(month=0;month<MONTHS;month++){
for(year=0,subtot=0;year<n;year++)
subtot+=*(*(array+year)+month);
printf("%-4.1f",subtot/n);
}
printf("\n");
}
linux下编译不通过
代码:
##将rain_year()的类型改为float
[
[email protected] test]$ gcc 10-11.c -o rain
10-11.c:39: error: conflicting types for 'rain_year'
10-11.c:23: error: previous implicit declaration of 'rain_year' was here
10-11.c:56: error: conflicting types for 'rain_month'
10-11.c:32: error: previous implicit declaration of 'rain_month' was here
10-11.c:68:5: warning: no newline at end of file
windows下给出警告但是编译通过,但是在rain_tot()内部的total值跟函数返回值total不一致。在windows编译的时候:
1、rain_year()需要返回total的值,但是如果将函数类型定义为float,就会报错;改为void就通过,这是为什么呢?
2、函数rain_year()中,在第44行输出的total值是200.1,第46行中return total这一步返回数值是36.0,这是为什么呢?
代码:
E:\C Programming\PrimerPlus\test>gcc 10-11.c -o rain
10-11.c:38:6: warning: conflicting types for 'rain_year' [enabled by default]
10-11.c:23:14: note: previous implicit declaration of 'rain_year' was here
10-11.c: In function 'rain_year':
10-11.c:52:5: warning: 'return' with a value, in function returning void [enable
d by default]
10-11.c: At top level:
10-11.c:55:6: warning: conflicting types for 'rain_month' [enabled by default]
10-11.c:32:5: note: previous implicit declaration of 'rain_month' was here
E:\C Programming\PrimerPlus\test>rain.exe
YEAR RAINFALL (inches):
2000 40.5
2001 37.2
2002 49.8
2003 38.0
2004 34.6
The total rainfall is 200.1 inches.
The number returned from rain_tot() is 36.0.
The yearly average is 7.2 inches.
The monthly averages are:
Yan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
7.3 7.3 4.9 3.0 2.3 0.8 0.4 0.4 1.2 2.1 4.2 6.2
E:\C Programming\PrimerPlus\test>