| ||||||||||||||||||||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
New Programmer Needs Help
Hey guys,
I am in my first semester of C++ programming and I have a question. I know how to do the basics as far as cin's and couts and stuff like that. I am trying to do an amortization program to calculate the mortgage payment for someone and my formula seems to be giving me the wrong answer. I have declared all my variables correctly and this is what is in my program: payment = (1+i/12)*n*(i/12*a)/(1+i/12)*n-1; cout <<" Mortgage Payment: " << payment << endl; What is wrong with this. I did a search on the board and saw that someone else needed help with their program and they broke the formula up into smaller parts. Is this what I should do as well? |
|
#2
|
|||
|
|||
|
Watch your ()
do you mean
payment = ((1+i/12)*n*(i/12*a))/((1+i/12)*n-1); if you wanted to evaluate everything to the left of the / sign and divide it by everything on the right of the / you need the extra set of ()......when your learning if your unsure about something always throw in ( ) even if you think they aren't needed I even think it makes code cleaner to use them for things such as if( (expression) && (expression)) sometimes in a case like that the inner () aren't needed but it makes the code look cleaner...when in dout use a lot of () to make sure the compiler knows what you mean |
|
#3
|
||||
|
||||
|
I have not checked your calculation but maybe writing it like this helps:
Code:
(1+i/12.0)*n*(i/12.0*a)/(1+i/12.0)*n-1; Breaking it up in parts might be the better thing to do anyway, it is much easier to read and mantain that way. What might be going wrong is that i/12 results in 0 because it is integer division. It should be 0.166667 but integers only hold integral numbers so it rounds down to 0. By typing i/12.0 you are forcing the result to a double because 12.0 is a double. To be honest, I always forget the exact rules for these kind of things. And I do not even try to remember them because I work with many languages which have different rules for these things. So to save myself trouble I always try to be explicit in the types of my subcalculations. Good luck
__________________
There is no such thing as C/C++, you either program C or C++ |
|
#4
|
||||
|
||||
|
p.s. Oh and at the end of your calculation, ...*n-1, you are multiplying by n and _after_ that subtracting one. Im suspecting that is not what you want? If so, use ...*(n-1) instead.
|
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > New Programmer Needs Help |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|