tags:

views:

127

answers:

4

I'm sorry, I just need an extra set of eyes, I'm second guessing myself. I'm working on translating from classic vb6 to c# and I've looked up the table on operator precedence however I'm still not working out correctly.

VB6

= _
        m_curAmountInvested * (1 + m_dblInterestRate / 12) ^ m_intMonthsToAttain + _
        m_curAddDeposits * ((1 + m_dblInterestRate / 12) ^ m_intMonthsToAttain - 1) / (m_dblInterestRate / 12)

C#

= (currentAmountSaved * Math.Pow((1d + interestRate) / 12d, numberOfMonths)) +
                    ((monthlySavingsAmount * (Math.Pow((1d + interestRate) / 12d, numberOfMonths) - 1d)) / (interestRate / 12d))
+1  A: 

There are two parts I'm not clear on:

  • The precedence of the exponent operator (^).
  • VB6 does some rounding automatically

Otherwise it looks okay, assuming your variable names line up.

You might want to actually test both version with a few values and makes sure they come out the same. And if they're different, check that better rounding hasn't made your C# code isn't actually more correct.

Update:
A quick check of the docs gives ^ the highest precendence. However, that's VB.Net. I couldn't find the docs for vb6, but StackOverflow agrees with it, and so I think you're okay in that department as well.

Joel Coehoorn
Exponentation has higher precedence over multiplication, in all languages where it is an infix operator, I believe.
Noldorin
The section on operator precedence seems to have been dropped from the online MSDN VB6 docs.
MarkJ
A: 

First factor in VB is m_curAmountInvested and in C# it is currentAmountSaved. That could be wrong.

alex
It looks like the OP generally took out pseudo-Hungarian-notation encodings in the variable name, so I would guess that it is intentional.
jprete
I meant Invested vs Saved not Hungarian vs not :)
alex
+3  A: 

Looks to me like you may have a problem in your C# code here:

Math.Pow((1d + interestRate) / 12d, ...)

Your VB6 code has:

(1 + m_dblInterestRate / 12) ^ ...

vb6 has a higher precedence for the * and / operators than the + and -, so the division will occur before the add. However, this is not true in the C# version because of the parentheses (i.e., the addition will come first, then the division).

Ed Swangren
ahhhh that would be the problem! many thanks, its been a long day.
Dave
+1  A: 

1 + m_dblInterestRate / 12 != (1d + interestRate) / 12d

binary sum has lower procedence than division. I think you are confusing it with the unary + operator (+5 == 5) which has higher procedence than division.

ggf31416
thanks again, that was the problem
Dave