Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a problem in my programming class. A person gets paid daily, day one is 1 penny, day two is 2 pennies, day three is 4 pennies, day five is 8 pennies and so on doubling each day. I wrote the following code but am having an issue with out put. When I put in 1 day it tells me 2 pennies instead of 1. I am sure this is an easy fix but my brain is fried and I am overlooking it.

Here is my code:

VB
Public Class Form1

Private Sub calculateButton_Click(sender As Object, e As EventArgs) Handles calculateButton.Click
Dim intDays As Integer
intDays = 1

Dim decPennies As Decimal
decPennies = 0.01

For intDays = 1 To cboDays.Text
decPennies = decPennies * 2

Next intDays
ansLabel.Text = decPennies.ToString("C")

End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For intDays = 1 To 20
cboDays.Items.Add(intDays)

Next
End Sub
End Class

Any help would be greatly appreciated.
Posted
Updated 28-Sep-15 14:49pm
v3
Comments
Richard Deeming 29-Sep-15 8:23am    
REPOST
You have already posted this question in the Visual Basic forum:
http://www.codeproject.com/Messages/5134907/Penny-for-Pay-question.aspx[^]

I would replace
VB
For intDays = 1 To cboDays.Text

with
VB
For intDays = 2 To cboDays.Text


Your program starting setting is 1 day.
To handle 0 day, you have to check for value 0 and in this case say result is 0 instead of doing normal program. Try to find the solution by yourself.
 
Share this answer
 
v2
Comments
BrianStrong 28-Sep-15 20:57pm    
That worked, but if I put 0 in the label it still says one. How could I fix this so that it says 0 instead?
Matt T Heffron 28-Sep-15 21:14pm    
I'd just "special case" the 0.
Check for it, and initialize decPennies to either 0 or 0.01.

However, there are MUCH simpler ways to calculate this!
No loop required (hint: each day's pay is a power-of-2 number of pennies)
Matt T Heffron 28-Sep-15 22:06pm    
On the 64th day you have been paid: 18446744073709551615 pennies. I'm sure I'd have retired well before then!
In actual pennies that's 4.6e16 Kg of pennies!
I explained what was wrong, and gave you a suggestion, in the VB.NET forum. Please do not post the same question in multiple forums.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900