#include<stdio.h>
#define YEARS 5
#define MONTHS 12
int main(void)
{
const float rain[YEARS][MONTHS] =//const限定一個變量可讀,不可被改變。雖然被限定了,但是仍然是變量,不可當做常量
{
{4.3, 4.3, 4.3, 3.0, 2.0, 1.2, 0.2, 0.2, 0.4, 2.4, 3.5, 6.6},//每年每個月降雨量
{8.5, 8.2, 1.2, 1.6, 2.4, 0.0, 5.2, 0.9, 0.3, 0.9, 1.4, 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.0, 0.6, 1.7, 4.3, 6.2},
{7.6, 5.6, 3.8, 2.8, 3.8, 0.2, 0.0, 0.0, 0.0, 1.3, 2.6, 5.2},
};
int year, month;
float subtot, total;//subtot每一年的降水總量,total五年的降水總量
printf("YEAR RAINFALL(inche)\n");
for (year = 0, total=0; year < YEARS; year++)//此循環將五年的總降水量求出
{
for (month = 0, subtot = 0; month < MONTHS; month++)//此循環將每一年的降水總量求出
subtot = subtot + rain[year][month];
printf("%5d %5.2lf\n", 2010 + year, subtot);
total = total + subtot;
}
printf("\nThe yearly average is %lf inches \n", total / YEARS);
printf("MONTHLY AVERAGES:\n");
printf("一月 二月 三月 四月 五月 六月 七月 八月 九月 十月 十一月 十二月\n");
for (month = 0; month < MONTHS; month++)
{
for (subtot=0,year = 0; year < YEARS; year++)
subtot = subtot + rain[year][month];
printf("%5.2lf", subtot / YEARS);
}
return 0;
}
輸出結果如下:
YEAR RAINFALL(inche)
2010 32.40
2011 37.90
2012 49.80
2013 44.00
2014 32.90
The yearly average is 39.399998 inches
MONTHLY AVERAGES:
一月 二月 三月 四月 五月 六月 七月 八月 九月 十月 十一月 十二月
7.34 7.30 4.88 3.00 2.30 0.60 1.20 0.26 0.48 1.72 3.58 6.74
陌生知識如下 :
1:控制浮點數的輸出位數
printf("%5d %5.2lf\n", 2010 + year, subtot);
%5是說將輸出的東西沒五個間隔打印一次。如:2010 32.40(2和三之間隔了五個)
.2是說將浮點數輸出小說點2位。如果不加2,只存在小數點,那麼浮點數的輸出將是八位全部輸出
2:const
在數組或者其他定義之前加上const是將該變量或者數組變為一個只可讀的變量,不可被改寫。但是就算只可讀,但是本質仍然是變量,不可當做常量來看待。