-2

Hi i'm currently working on a problem I got in my Highschool C++ class.

Were supposed to write a program which contains arrays in which you can store the highest monthly temperature and the lowest. And also, the program should have a loops to calculate each of the following:

  • Yearly Average High Temperature

  • Yearly Average Low Temperature

  • Highest Monthly Average High Temperature

    • Lowest Monthly Average High Temperature

I'm stuck with the monthly highest and lowest average temperature and could need some help. My code so far is:

#include <iostream>

using namespace std;

int main()

{

class location;
int high[12];
int low[12];
int i = 1;
int avgh, avgl;


//set location
std::string location;
std::cout << "Where is the location of your data:   ";
std::getline(std::cin, location);

cout << endl << endl;

//initialize array high
for (i = 1; i < 13; i++)
{
    cout << "Enter temperature high of month " << i << "    ";
    cin >> high[i];
    avgh += high[i];
}

cout << endl << endl;

//initialize array low
for (i = 1; i < 13; i++)
{
    cout << "Enter temperature low of month " << i << "    ";
    cin >> low[i];
}

cout << endl << endl;

//adds highs together
    for (i = 1; i < 13; i++)
{
    avgh += high[i];
}
cout << "The yearly average high is:   " << avgh/12 << endl;

    //adds lows together
    for (i = 1; i < 13; i++)
{
    avgl += low[i];
}
cout << "The yearly average low is:   " << avgl/12 << endl;



return 0;
}
  • 1
    FYI arrays are 0-indexed in C++, which means that the valid elements in an array of length 4 will be at indices 0,1,2 and 3. You might want to get [a good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to help you with the basics and the class, actually. – jaggedSpire Nov 15 '16 at 22:01
  • you are going well, just remember that arrays start from 0 not from 1 – Marco Nov 15 '16 at 22:02
  • `for (i = 1; i < 13; i++)` -- Get into the habit of using `0` as the starting index. Arrays in C++ start from `0`, not `1`. Trying to fake things by starting arrays at `1` artificially can and will lead to off-by-one errors and buffer overruns when the program gets much larger. – PaulMcKenzie Nov 15 '16 at 22:02
  • Your arrays have one dimension. – stark Nov 15 '16 at 22:09

1 Answers1

1
for (i = 1; i < 13; i++)

This is too wrong. It should be:

for (i = 0; i < 12; i++)

Indices in c++ are zero-based.


//adds highs together
for (i = 1; i < 13; i++)
{
    avgh += high[i];
}

You have already done this during the initializing stage so this leads to wrong results. However, you did not do the same for low, so you can keep the low part. Anyway, it is better to do them both while initialization or both separated in order to keep a straight unified way.

Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160