質問

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:

  • monthlyInterest = ((APR / 100) + 1)^(1/12)

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:

  1. yearlyInterest ~1.19
  2. monthlyInterest ~1.015...

But the result my debugger is giving me is:

  1. yearlyInterest ~1.19
  2. monthlyInterest = 1

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>
役に立ちましたか?

解決

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 ..

他のヒント

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)

One thing is clear and that is that 1/12 == 0 (try 1./12).

Danger, Will Robinson! 1/12 is not the same as 1.0/12.0.

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top