Unexpected result, Cant find the error

int main()
{
double rainfall[12];
double total = 0;
double avg = 0;
double maxRain = 0;
double minRain = 0;
double tempRain = 0;


for (int i = 0; i < 12; i++) {
cout << "Please enter rainfall for month " << i + 1 << ": " << endl;
cin >> rainfall[i];
total += rainfall[i];

}


avg = total / 12;

maxRain = rainfall[0];
minRain = rainfall[0];

for (int i = 1; i <= 12; i++) {
tempRain = rainfall[i];
if (tempRain < minRain)
minRain = tempRain;
if (tempRain > maxRain)
maxRain = tempRain;
}
cout << total << endl;
cout << avg << endl;

cout << maxRain << endl;
cout << minRain << endl;
}





The total prints fine, the average prints fine, the maximum prints fine, what am I missing for the minimum to not be printing properly?
The second for loop:
1
2
// for (int i = 1; i <= 12; i++) {
for (int i = 1; i < 12; i++) {


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

int main()
{
    const int NMONTHS = 12 ;
    double rainfall[NMONTHS] {} ;
    double total = 0;

    for( int i = 0; i < NMONTHS ; ++i )
    {
        std::cout << "Please enter rainfall for month " << i+1 << ": " ;
        std::cin >> rainfall[i];
        total += rainfall[i];
    }

    const double avg = total / 12;

    double maxRain = rainfall[0];
    double minRain = rainfall[0];

    for( int i = 0; i < NMONTHS ; ++i )
    {
        if( rainfall[i] < minRain ) minRain = rainfall[i] ;
        if( rainfall[i] > maxRain ) maxRain = rainfall[i] ;
    }

    std::cout << "  total: " << total << '\n'
              << "average: " << avg << '\n'
              << "minimum: " << minRain << '\n'
              << "maximum: " << maxRain << '\n' ;
}
Make your second for loop just like the first one:

1
2
for (int i = 0; i < 12; i++) {
tempRain = rainfall[i];


Arrays start at 0.

Please always use code tags: http://www.cplusplus.com/articles/z13hAqkS/ and post code that we can compile.

l like to always put digits before and after the decimal point for doubles:

1
2
3
4
5
6
7
double total = 0.0;
double avg = 0.0;
double maxRain = 0.0;
double minRain = 0.0;
double tempRain = 0.0;
// ...
avg = total / 12.0;


It sounds pedantic, but it will save you trouble one day.

Instead of the magic value of 12 everywhere make it a const variable, and use that:

1
2
constexpr unsigned int Size =12; // could use const instead of constexpr
double rainfall[Size];

but then be sure to do this:

avg = total / static_cast<double>(Size);

I made Size an unsigned int because it shouldn't be negative, but it is technically better to make it std::size_t, as this is what is used for the size of containers in C++.

Good Luck !!
Last edited on
Thank you guys!
Topic archived. No new replies allowed.