Program doesn't work correctly.

I cannot find a problem within the code. My highest, average, and total come out to be the correct number. My lowest number comes out to be around negative two million every time. Please help. Thank you!

// Practice 31.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;


int main()
{
const int SIZE = 12;
double rainfall[SIZE];
int lowest = rainfall[0];
int highest = rainfall[0];
double total = 0;
for (int i = 0; i < 12; i++) {
cout << "Enter rainfall for month " << i + 1 << endl;
cin >> rainfall[i];
if (rainfall[i] < 0) {
cout << "Please enter a postive number" << endl;
cin >> rainfall[i];
}

}
for (int i = 1; i < SIZE; i++) {
if (rainfall[i] < lowest) {
lowest = rainfall[i];
}
if (rainfall[i] > highest) {
highest = rainfall[i];
}
}
for (int i = 0; i<SIZE;i++){
total += rainfall[i];
}
double average = total / SIZE;
cout << "The total amount of rainfall is "<< total << endl;
cout << "The average amount of rainfall is "<< average << endl;
cout << "The highest amount of rainfall is "<< highest << endl;
cout << "The lowest amount of rainfall is " << lowest << endl;

system("pause");
return 0;
}

closed account (E0p9LyTq)
You are creating lowest and highest when your rainfall array is uninitialized, it is full or garbage values.

Create lowest and highest after you get your rainfall values.

The two variables should be double, the same as your array. There will be rounding/conversion errors when assigning a double to an int.

And PLEASE, learn to use code tags, it will make reading your source much easier.
http://www.cplusplus.com/articles/jEywvCM9/

You can edit your post and add the tags.
Hi,


1
2
int lowest = rainfall[0];
int highest = rainfall[0];


In these lines, the data is not yet in the array, so the values could be any garbage value like -2 million.

You can fix this by initialising the array to zero values like this, using at least the c++11 standard:

double rainfall[SIZE] = {};

Please always use code tags:

http://www.cplusplus.com/articles/z13hAqkS/
Last edited on
Alright I got it working. Thank you. It's my first time using this site so sorry about not using code tags. Thank you again.
Topic archived. No new replies allowed.