I've tried different ways and referred to the source code provided but could never seemed to get the values from the array in. If I do not include the int in the for statement, I'd be getting Nan values. With the int statement, the value becomes 0.00 but it would not make sense as the floats are now of type int. Please help me see where my code had went wrong. Thanks!
#include <stdio.h>
#include <stdlib.h>
#define Years 5
#define Months 12
int main(void)
{
int year = 0, month = 0;
float monthlytotal = 0, yearlytotal = 0;
printf("\aWelcome. This is a generated simple weather analysis of Aruba's weather for the last 5 years.\n");
float rainfall[Years][Months] = {
{ 126.6, 186, 6.2, 89.8, 193.8, 162.8, 168.6, 139.2, 118.9, 181, 290.2, 292.6 },//2016
{ 197.6, 158.4, 136.2, 208.6, 190, 106, 79.6, 84.2, 124.4, 120.8, 268.6, 371.2 },//2017
{ 287, 14.8, 44.6, 61.2, 132.2, 182.6, 143.2, 121.6, 144.4, 234.4, 169.6, 172.6 },//2018
{ 63.6, 31.6, 72.2, 174.8, 69, 173.8, 12.2, 11.8, 22.8, 176.8, 137.4, 421.5 },//2019
{ 88.4, 65, 108.8, 188, 255.6, 233.8, 140.8, 103.4, 150.2, 78.8, 220.6, 253.2 }//2020
};
printf("Based on the data collected from WEBBA, here are the results.\n");
printf("Year\t\t\tAmt of rain\n");
for (year = 0, yearlytotal = 0; year < Years; year ) {
for (month = 0, monthlytotal = 0; month < Months; month ) {
monthlytotal = rainfall[Years][Months];
}
printf("%d\t\t.2f\n", 2016 year, monthlytotal);
yearlytotal = monthlytotal;
}
return 0;
}
CodePudding user response:
monthlytotal = rainfall[Years][Months];
should be
monthlytotal = rainfall[year][month];
Note that clang's -Warray-bounds (on by default in clang) would have found the problem at compile time.
Note that gcc and clang's -fsanitize=address would have found the problem at run time.
