i have a text file with 30 records of dates and numbers(rainfall)
i want to find the average rainfall between two dates so i want to be able to enter two dates and the output will give me the average rainfall of those two dates
a record will look like this:
1 12 2009 2.5
2 12 2009 5.1
and so on til 30
heres what i have so far. all this code does so far is display the date
1 2 3 4 5 6 7 8 9 10 11 12
int day = 0, month = 0, year = 0;
cout <<"Enter a date : " << endl;
cin >> day,month,year;
for (int i = 0; i < 30; i++)
{
if (day, month, year == date[i].day, date[i].month, date[i].year)
{
infile >> date[i].day >> date[i].month >> date[i].year >> report[i].rainfall;
cout << "rainfall for the "<< date[i].day << "/" << date[i].month << "/" << date[i].year << " is " << report[i].rainfall << endl;
}
}
i havn't got the average yet because i want to make sure the correct date is displaying which its not. The output is displaying all dates instead of the date i entered
You're already accessing the data in your ifs. Now just save them in a variable. Make sure to declare the variable outside of the for loops, because you'll need them afterwards.
You can either use N variables to store all N rainfalls (N = 2 in your question, but in the general case where you want multiple days, you'll need N variables) and then sum and divide at the end, or use one variable to store the total. In the first case, you'll need a separate variable for each and use the assignment operator ('=') inside the ifs. The latter case needs one variable (initialize at 0!) and the addition operator ('+=').
double sum = 0; //a running total
for( int i = 0; i < N; i++ ) //loop though the "report" array, where "N" is it's length
sum += report[i].rainfall; //add to the running total
double avg = sum / N; //calculate the average
report[N] would be outside the array's boundaries. Array indexes must be an integer in [0, N) i.e. [0, N-1].