I need help with counting the months in my code. I always end up with 1 more month than i need after the program compiles. The assignment i was given is to use a sentinel value in a while loop.. While the sentinel value is working fine i was also told to enter the months into the program. So we are calculating the amount of rainfall that is input while also counting the month up by 1 for each input until the sentinel value is input.(-1) The sentinel value works, but the months are not being counted right. Can someone please point me in the direction? Any pointers will help, thank you.
[code]
// This program illustrates the use of a sentinel in a while loop.
// The user is asked for monthly rainfall totals until a sentinel
// value of -1 is entered. Then the total rainfall is displayed.
// Chase Garland
#include <iostream>
using namespace std;
int main()
{
double month= 1;
float total = 0, rain;
int sum= 0;
cout << "Enter the total rainfall for month " << month << endl;
cout << "Enter -1 when you are finished" << endl;
cin>> rain;
while (rain !=-1)
{
sum = sum + rain;
month= month + 1;
cout << "Enter the total rainfall in inches for month "
<< month << endl;
cout << "Enter -1 when you are finished" << endl;
cin>> rain;
}
if (month == 1)
{
cout << "No data has been entered" << endl;
}
else
{
cout << "The total rainfall for the " << month
<< " months is "<< sum << " inches." << endl;
}
system("PAUSE");
return 0;
}
consider a do while instead of cin, while (cin) format, you can just have do cin while which is cleaner.
consider x++; or x +=1 instead of x = x+1 format.
now, about your counting.
month starts at 1. they enter ONE value, and month becomes 2.
therefore you have 2 months, one value.
three months, 2 values.
maybe month should start at zero? I think you just have bad logic in how you choose to count.
I don't think you need any pointers here. (sorry, bad c++ joke).
It's not that it is bad logic, it is that this is how the professor told us to do it. It did not make any sense to me, but to get a good grade i am trying to do what he asks as closely as possible. I also already tried starting the months off at zero, and it works but the program has to print the number of month onto the screen. So when this happens the code prints 0 in the first month slot. We are supposed to start it at one, but i cannot get it to work. Thanks for replying and trying to help.