2

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))
David
  • 19,389
  • 12
  • 63
  • 87

4 Answers4

3

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 S.
  • 122,712
  • 22
  • 185
  • 265
1

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.

Community
  • 1
  • 1
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • Exponentation has higher precedence over multiplication, in all languages where it is an infix operator, I believe. – Noldorin Oct 09 '09 at 21:32
  • The section on operator precedence seems to have been dropped from the online MSDN VB6 docs. – MarkJ Oct 10 '09 at 20:23
1
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.

TAbdiukov
  • 1,185
  • 3
  • 12
  • 25
ggf31416
  • 3,582
  • 1
  • 25
  • 26
0

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

alex
  • 74,215
  • 9
  • 49
  • 57
  • 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 Oct 09 '09 at 21:31
  • 2
    I meant Invested vs Saved not Hungarian vs not :) – alex Oct 09 '09 at 21:33