Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Working on an assignment using c# and visual studio. I want the user to type in how many days they worked and the pay for each day to show in a listbox. However, the pay needs to double each day. So day 1 they get 1 penny, day 2 they get 2 pennies, day 3, they get 4 pennies, etc. Having trouble getting to increase by 2x, while still keeping the count only going up by one day.

What I have tried:

//declare the variables
double dblDays;
double dblPay;
int intCounter=1;



if (Double.TryParse(txtDays.Text, out dblDays))
{
for (intCounter = 1; intCounter <= dblDays; intCounter ++)
{
dblPay = (dblDays*.01) * intCounter;
lstDays.Items.Add("Pay for Day" + intCounter.ToString() + "=" + dblPay.ToString("c"));
lblTotalPayEarnedTotal.Text = dblPay.ToString("c");
Posted
Updated 27-Nov-18 9:13am

1 solution

change
dblPay = (dblDays*.01) * intCounter;
to
dblPay = (dblDays*.01) * Math.Pow(2,(intCounter-1));

because in math,
2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
etc...
 
Share this answer
 
v4
Comments
George Swan 28-Nov-18 5:00am    
You can do it in one line with linq
Enumerable.Range(1, days).Aggregate((r, i) => r+(int)Math.Pow(2,i));
Richard Deeming 28-Nov-18 11:36am    
That won't produce the correct result. :)

Because you're starting the range at 1, you end up doubling the salary on the first day instead of the second day.

But if you change the range to start at 0, you'll still get the wrong answer, because you haven't provided a seed value. Without a seed value, Aggregate will not call the aggregation function on the first value in the sequence, so you end up paying zero for the first day.

There are a few ways to fix it:
Enumerable.Range(0, days).Aggregate(0, (r, i) => r + (int)Math.Pow(2, i));
Enumerable.Range(0, days).Aggregate((r, i) => r + (int)Math.Pow(2, i)) + 1;
Enumerable.Range(1, days).Aggregate((r, i) => r + (int)Math.Pow(2, i - 1));
Enumerable.Range(0, days).Select(i => (int)Math.Pow(2, i)).Sum();


However, a simpler option would be to avoid LINQ and just calculate the result directly:
Math.Pow(2, days) - 1;
George Swan 28-Nov-18 15:46pm    
Excellent,Richard. I must test before I post
Richard Deeming 28-Nov-18 11:18am    
This is C# - ^ is the Xor operator.
^ Operator (C# Reference) | Microsoft Docs[^]

For powers of two, you either need to use Math.Pow, or the left-shift operator. :)
Alek Massey 28-Nov-18 11:42am    
Thanks, I guess I had VB on the brain, fixed.

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