Student Programmer, help with math step

Pages: 12
I have started with this I added my penny loop to the original for loop for the days. I am still figuring out the middle and last part. I can't figure out how to my pennies stop. When I orginally started this program with this but changed it before I posted the question because I couldn't figure out how to make it work.
1. I started day with one and pennies with one.
2. I want the day to stop with the user input.
3. I cannot figure how to make the pennies stop.
4. Day will increment 1 each loop till it reaches days
5. pennies will double with each loop.

 
for(day = 1, pennies = 1; day <= days, pennies <= days; day++, pennies*2)
There's a logic error right there. The comma operator can be understood as, "do then, and do this". But when you want to evaluate the result of an expression, only the last value counts.

Example:
int x = (4, 7, 3) ;
What value will be assigned to x? The answer in this example is 3 since that is the right-most expression.

Now look at the condition used in the for loop:
for (day = 1, pennies = 1; day <= days, pennies <= days; day++, pennies*2)
You see what happens here? It is as if you had put just:
for (day = 1, pennies = 1; pennies <= days; day++, pennies*2)
I think that is not what you want. the loop should be checking only the other condition, day <= days and the second part should be deleted, it is superfluous.

There is another error too. Look at this code: day++, pennies*2
Now there is no problem with having more than one expression here, that's ok.
However,
day++ means add 1 to the current value of day and store the result in day.
But pennies*2 means multiply the current value of pennies by 2, and don't store the result anywhere. It should be either:
pennies = pennies*2 or more concisely, pennies*=2

So now the complete line reads like this:
 
    for (day = 1, pennies = 1; day <= days; day++, pennies*=2)


See the tutorial page for help with operators, in particular compound assignment and the comma operator. http://www.cplusplus.com/doc/tutorial/operators/


Last edited on
thank you I will change the ending. I tried looking it up in my book and couldn't locate it, i know its in there.
Chervil

Thank you so much. You just cleared up a big headache for me.
One more problem with this program. I am using user input validation. The user cannot have worked less than 1 day or more than 31. It works fine when I put in zero for days, it says cannot have worked less than zero days but when I put in 32 it doesn't display the message. here's how I wrote it.

1
2
3
4
if (days <= 1  || days >= 31)
	{
		cout << "You cannot have worked less than 1 day or more than 31." << endl;
	}


I tried making it two separate statements but that didn''t work to well.
Topic archived. No new replies allowed.
Pages: 12