I'm writing a program and one of the requirements is to find aggregate rainfall from user input for each month. I wrote the code for about one month so far but the total I get is way to high. Can't figure out why/
#include<iostream>
#include<math.h>
#include<conio.h>
usingnamespace std;
float January(float);
int main(){
int month_Rain;
int ave_daily;
int ave_month;
int year_Rain;
int highest_month;
int lowest_month;
int highest_year;
int lowest_year;
int Jan_rain;
float rainfall=0;
cout<<"Please enter the rainfall for january\n";
month_Rain = January(Jan_rain);
cout<<"the rainfall for this month is: ";
cout<<Jan_rain<<endl;
return 0;
getch();
}
float January(float){
float Jan_rain=0;
int days=1;
float rainfall;
float daily_rainfall[days];
while(days <=31)
{ cout<<"\nPlease enter the rainfall for day " <<days<<": ";
cin>>rainfall;
days++; }
daily_rainfall[days]=rainfall;
Jan_rain += daily_rainfall[days];
return Jan_rain;
}
How can this be compiled without error while your array size of daily_rainfall is not constant? I think array may not be needed... and you cout Jan_rain while you are suppose to cout month_Rain.
Scope. Better indentation could show it more clearly. I'll write a version that does about the same as yours:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
float January()
{
float daily_rainfall[1]; // short, uninitialized
int days = 31;
cout<<"\nPlease enter the rainfall for day " <<days<<": ";
float rainfall;
cin>>rainfall;
daily_rainfall[32] = rainfall; // out of range error
float Jan_rain = 0;
Jan_rain += daily_rainfall[32]; // out of range error
return Jan_rain;
}
There is no loop in my version, because you never assign to array or add to sum inside your loop. That is the scope error.
You should not be able to declare a variable-lenght-array in C++, so float daily_rainfall[days]; is bad.
You don't even need the array. Just add to sum on every iteration.
Do not create 12 similar functions. Make one and pass the number of days as parameter.
I realized it was a scope error when I tried to move the loop into main and i have no idea how I was able to do it in the function because when I tried to do it in the header it gave the relevant error. Thanks I'll try
Any ideas on how to identify the months once I pass the number of days as a paramameter february will be easy to identify but what about everything else?