double monthlyPayment ()
{
double loanAmount, rValue, i;
int r, m, t, n;
cout <<"Enter the loan amount: ";
cin >> loanAmount;
cout << endl;
cout <<"Enter the interest per year as a number: ";
cin >> r;
cout << endl;
cout <<"Enter the payments in one year: ";
cin >> m;
cout << endl;
cout <<"Enter the number of years for the loan: ";
cin >> t;
cout << endl;
//the result of (i) is 0.00 i do not get how that is happening??!!
i = static_cast <double> (i = r/(m*100));
cout << "test " << i << endl;
n = m*t;
cout <<"test2 " << n << endl;
rValue = loanAmount * i / (1 - pow(1+i,-n));
//This is a test only output statment
//cout <<"The monthly payment is: $ " << rValue << ".\n\n";
return rValue;
}
The problem is that you are dividing integers. In integer division the / operator gives the quotient.eg. 2/5 = 0 NOT 0.4
The % operator gives the remainder. eg. 2%5 = 2
You are getting 0 because r < 100*m.
Easy fix is to make all your variables doubles.
Other way: i = static_cast <double>(r)/static_cast <double>(100*m);
As I know,there is no difference,except that in a long listing of code,it is easier to find "static_cast " keywords in case of debugging and finding errors.(since casting my cause data loss and error)
Of course you can print out a double value as you do int values.
But in the above code you defined r as integer.If you want to enter values such as 5.25 define it as [b]double.[/b]
What oldnewbie is doing is creating temporary doubles from the integer values of r and m. He then performs the necessary operations, multiplies the result by an integer (careful...), and then the doubles are discarded.
What fun2code is going is using a static_cast, the details of the implementation of which I am not 100% certain of. static_cast is good for conversions of integral types, and it's less restrictive and has less of an overhead than dynamic_cast (which is safer, by the way).