Reputation: 581
I am doing a homework assignment for my C++ class, and am trying to do what I consider a fairly simple math function, but I'm getting stumped because it is not returning what I expect it to return. Basically, it's just an APR problem and I am trying to convert from APR to monthly interest. My instructor has given us this formula to calculate this:
So this is the code I am using. I separated yearlyInterest from the monthlyInterest calculation because I was making sure I wasn't making a simple mistake:
double balance, payment, APR;
cin >> balance >> payment >> APR;
const double yearlyInterest = (APR / 100) + 1;
const double monthlyInterest = pow(yearlyInterest, 1/12)
Using the inputs 1000, 100, and 19.9, the results I get in my physical calculator, and what I am expecting are:
But the result my debugger is giving me is:
So basically, I am asking why my monthlyInterest is incorrect? I don't believe it is a type issue because pow() will output a double. Also, I don't think that the decimal should overflow the double type, it's not that big and I only need a few digits of accuracy anyway. So if anyone can help me determine the mistake I made, I would appreciate it.
Sidenote: I have included the following. I use instead of because it is what I learned on. If this is a problem, I can change it.
#include <iostream>
#include <cmath>
Upvotes: 1
Views: 701
Reputation: 64
You need to make the expression 1/12
return a float value to force floating point division instead of integer division.
change:
const double monthlyInterest = pow(yearlyInterest, 1/12);
to:
const double monthlyInterest = pow(yearlyInterest, 1.0/12);
const double monthlyInterest = pow(yearlyInterest, 1/12);
integer division of 1/12
truncates the fractional result to 0
. Thus the above line would be processed as
const double monthlyInterest = pow(yearlyInterest, 0);
and a number raised to the 0 power equals 1. Thus in your case monthlyInterest is assigned the value 1.
Upvotes: 0
Reputation: 2704
1/12
and APR
are performing integer division.
If you explicitly use floating point numbers you'll get your expected results.
Instead of 1/12
use 1/12.
(notice decimal point)
and instead of APR/100
use APR/100.
(notice decimal point)
Upvotes: 3
Reputation: 33046
In this line:
const double monthlyInterest = pow(yearlyInterest, 1/12)
1/12
gets rounded to 0 (because it's integer division) and the result is 1
. Replace with:
const double monthlyInterest = pow(yearlyInterest, 1.0/12)
Mind the .
.
Upvotes: 7
Reputation: 143061
One thing is clear and that is that 1/12
== 0 (try 1./12
).
Upvotes: 1