Need some help with calculating the fixed monthly payment (P) required to fully amortize a loan of L dollars over a term of n months at a monthly interest rate of i. The given formula is: P = L[i(1 + i)n]/[(1 + i)n - 1]. I wrote a code but it didn't calculate Payment. I'm wondering if it is because I use double type together with int (for number of months) or the problem with formula?! Please help.
#include<stdio.h>
#include <math.h>
double calculatePayments(double rate, double loan, int payments);
int main() {
double principal, i, monthlyP;
int month;
printf ("Enter the principal amount: ");
scanf ("%f", &principal);
printf ("Enter the interest amount: ");
scanf ("%f", &i);
printf ("Enter the term in months: ");
scanf ("%d", &month);
monthlyP = calculatePayments (i, principal, month);
printf ("The monthly payment amount is %.2f: ", monthlyP);
return 0;
}
double calculatePayments(double rate, double loan, int payments) {
double mPayments;
mPayments = loan*(rate*(1 + rate)*payments)/((1 + rate)*payments - 1);
return mPayments;
}
Your scanf() requests %f format for a double; it should be %lf.
In addition to the need to fix the input (%lf instead of %f for doubles), I think your payment formula is wrong: since the future value of money grows exponentially, the formula should feature raising numbers to a certain power, which it does not.
The correct formula looks as follows (from here):
Since the loan needs to be paid off completely, FV is equal to zero.
Since pow(i+1, n) is used twice, it's a good idea to compute it once, and use the resultant variable in two places. The final version of this computation looks like this:
double calculatePayments(double rate, double loan, int payments) {
double mul = pow(1+rate, payments);
return (loan * mul * rate) / (mul - 1);
}
Demo on ideone computes the payment on $100,000 at 0.004% per month for 30 years at $524.67, which is the same value that excel's PMT function returns.
Note : When you enter the rate of 5.6% in your formula and in another calculator, don't forget that your formula takes the rate per month, not per year. Therefore, the rate that you plug into outside calculators must be 12 times what you enter into your calculator (for 5.6% annually you should enter 0.00466666
One of the first rules of debugging is to make sure you print the inputs to ensure that the program got the values you expected. It didn't, because you wrote:
scanf ("%f", &principal);
Since principal is a double, the format needs to be "%lf". Repeat for the interest rate. You should also check that the inputs succeeded:
if (scanf("%lf", &principal) != 1)
{
fprintf(stderr, "Failed to read principal\n");
return(1);
}
If you'd printed out the input values, you'd have known what was wrong immediately.
Read what dasblinkenlight said.
Also,
Fix your declarations and the variables you are using scanf() for.
principal should be loan. month should be payments.
i is okay. You need to calculate the monthly decimal number of the percentage given.
For instance,
interest = (i/100) /12;
Do that before your function call. Then just basically use dasblinkenlight's function at the bottom of your main.
hope you score a "10" ;)
Related
There's some problem with the 'calculate the total' part but I'm unsure what it is. Everything else runs fine besides it.. I get the "result_pointer != nullptr" error everytime.
void CalculateTotal(double pricePerGallon, double* totalPtr)
//input price per gallon
//declare, ask and get the number of gallons
//calculate the total
//input/output parameter for the total
{
//declare, ask and get the number of gallons
int numGal = 0;
double tot;
printf("Enter the number of gallons requested: ");
scanf("%d", numGal);
//calculate the total
tot = numGal * pricePerGallon;
*totalPtr = tot;
printf("Your total is %f.", totalPtr);
}
unsure if it matters, but I called it in another function definition like so:
CalculateTotal(itemNumber, &total);
(I'm just learning programming for my class, so the simpler the explanation, the better. This is not C++ btw, just C.)
scanf should get a pointer, so your call to the function is wrong and should be as follows:
scanf("%d", &numGal);
You also have a bug in your call to printf, which should be as follows:
printf("Your total is %f.", *totalPtr);
You need to use the indirection operator due to the fact that totalPtr is a pointer.
This is my program below to calculate the mpg value, then convert it
to liter-per-100-km value.
My question is why when I define the mpg variable as you see in comment number 1 my program outputs wrong values but when I define it as you see on comment number 2, the program outputs correct values?
#include <stdio.h>
#define GAL_TO_LIT 3.785
#define MILE_TO_KM 1.609
int main()
{
float miles;
float gallons;
float mpg; //1 float mpg = miles / gallons;
printf("Enter the number of miles traveled: ");
scanf("%f", &miles);
printf("Enter the number of gallons gasoline consumed: ");
scanf("%f", &gallons);
mpg = miles / gallons; //2
printf("The miles-per-gallon value is: %.1f\n", mpg);
printf("The liters-per-100-km value is: %.1f\n",
100. / mpg * GAL_TO_LIT / MILE_TO_KM);
return 0;
}
When program execution reaches the line with the first comment, miles and gallons have indeterminate values since they have not been initializes nor assigned to. Accessing those values is undefined behaviour.
In the line with your 2nd comment miles and gallons have already got values by scanf() and everything is fine.
Actual values of miles and gallons have been assigned once you use scanf. Before that when the variable is initialized both variables are having some random "garbage" value.
I can see you have just started programming and my only advice will be to always perform the operations on variable once the proper value has been assigned to them (like in comment 2).
As part of my first homework assignment in an Intro to Dev class, I have to write a currency exchange program in C. I've met most of the assignment requirements, but I'm stuck on two parts.
1) When I enter 30000 as the input value, I get 2 new values for the two exchange rates, but I'm then supposed to show the difference as the final output. When I do this, the rounding doesn't work out and the difference is one cent larger than the actual difference. I know this problem was covered in class, but even when I try to match the examples from the text (splitting up dollars and cents), I end up one cent off.
2) When I enter 5000 as the input value, the final difference comes out as "16.9", but should have two digits after the decimal point. No matter how I format the output, I can't get something that shows accurate formatting on both the entry for 5000 and the entry for 30,000.
Since this is our first assignment in an intro class, we can only use a few different arguments/commands. We aren't allowed to use double for anything. The instructions specifically mention using fabs() for absolute values in reporting the difference, which I've done here. I'm assuming at least the first problem is in my sequencing of fabs() and floor(), but being a newbie I'm pretty clueless about where to look for the actual problem. Any suggestions or assistance would be greatly appreciated!
// This program compares a specified quantity of US Dollars to Czech
// Korunas at two different fixed exchange rates.
#include <stdio.h>
#include <math.h>
int kor; // User-entered Korunas
const float EXRATE1 = 42; // Constant Exchange Rate 1
const float EXRATE2 = 37; // Constant Exchange Rate 2
float dolex1; // User-entered Koruna value with Exchange Rate 1 applied
float dolex2; // User-entered Koruna value with Exchange Rate 2 applied
float diff; // Difference between two values
int dollars; // Diff value expressed as absolute, dollar digit
float cents; // Diff value expressed as absolute, cents digits
FILE *diskfile;
//Main function
main(){
// Get information from user
printf("*** Koruna Exchange App ***\n\n");
printf("How many korunas do you have in your savings account?\n");
scanf("%d", &kor);
printf("The exchange information for %d korunas is now being recorded.\n", kor);
// Combine user-entered value with various exchange rates to get new values
dolex1 = kor / EXRATE1;
dolex2 = kor / EXRATE2;
// Find difference between new values, then get absolute value
diff = fabs (dolex2 - dolex1);
//Separate dollars and cents
dollars = floor (diff);
cents = (diff-dollars) * 100;
//Open and create file
diskfile = fopen("c:\\class\\test-ke.txt","w");
//Display results
fprintf(diskfile,"For %d korunas:\n", kor);
fprintf(diskfile,"At the rate of %.0f korunas per U.S. dollar,\n", EXRATE1);
fprintf(diskfile,"you have %.2f U.S. dollars.\n", dolex1);
fprintf(diskfile,"At the rate of %.0f korunas per U.S. dollar,\n", EXRATE2);
fprintf(diskfile,"you have %.2f U.S. dollars.\n\n", dolex2);
fprintf(diskfile,"The difference is %d.%.f U.S. dollars.\n", dollars, cents);
fclose(diskfile);
return 0;
}
please replace
fprintf(diskfile,"The difference is %d.%.f U.S. dollars.\n", dollars, cents);
with this EDIT:
fprintf(diskfile, "The difference is %.2f U.S. dollars.\n", dollars+cents/100);
The problem I've been having is that my code will get stuck either in an infinite loop or will have a stack overflow problem and begin producing negative numbers during calculations.
I am aware that this issue is coming from my while loop and also think the issue probably lies with the formula I am using being the line i = (r / 12)*(b - p + temp);.
However I am unsure of how to fix this. My formula is trying to calculate the interest paid on a fixed interest loan for each month over 12 months and print that to the screen with the remaining balance. This is supposed to continue until the balance reaches 0.
#include <stdio.h>
// main function
int main()
{
// variable declarations
float r = 0.22; // interest rate
float b = 5000.0; // amount borrowed
float p; // payment amount
int m = 1;
float temp, ti = 0;
float i;
// Take in data from user
printf("Please enter the amount you wish to pay monthly: \n");
scanf("%f", &p);
printf("\n");
//display interest rate, initial balance, monthly payment
printf("r = %.2f\nb = %.1f\np = %.1f \n\n", r, b, p);
// Month by month table showing month interest due/paid and remaining balance
i = (r / 12) * b;
temp = i;
printf("%d %.2f %.2f\n", m,i,b);
m++;
while (i > 0) {
i = (r / 12) * (b - p + temp);
b = (b - p + temp);
ti += temp;
temp = i;
printf("%d %.2f %.2f\n",m, i, b);
m++;
}
printf("\n");
printf("total interest paid: %.2f\n", ti);
return 0;
}
Well, if I'm doing the math correctly it looks like if you enter a value less than 91.67 for P you are going to get stuck in an infinite loop because the monthly payments are less than the interest accusing on the debt; so you might want to add a check for that.
As an aside if you named your variables as Interest, Base, etc. you wouldn't need the comments and the code would be easier to read.
Also since you are printing out the payment info until balance is zero you should loop while b > 0.
The program works as expected.
The only problem is, if your monthly payment are less
than the interest rate - then the amount you need to pay back
grows exponentially and the program never stops.
Enter any number >= 92 and it seems to work.
Is 22% p.a. interest rate correctly?
I don't see this generating an infinite loop but it would become a problem if your repayment is higher than the matured interest, which with your starting parameter it means anything below 91.67.
You may have a wrong end condition so there is always a negative line printed, though.
I'm currently taking a basic intro to C programming class, and for our current assignment I am to write a program to convert the number of kilometers to miles using loops--no if-else, switch statements, or any other construct we haven't learned yet are allowed. So basically we can only use loops and some operators. The program will generate three identical tables (starting from 1 kilometer through the input value) for one number input using the while loop for the first set of calculations, the for loop for the second, and the do loop for the third.
I've written the entire program, however I'm having a bit of a problem with getting it to recognize an input with a decimal component.
The code reads in and converts integers fine, but because the increment only increases by 1 it won't print a number with a decimal component (e.g. 3.2, 22.6, etc.).
Can someone point me in the right direction on this? I'd really appreciate any help! :)
It's not clear what you're trying to get as output. You use the example of starting with 3.2, so based from that, and based on your current program, your output is:
KILOMETERS MILES (while loop)
========== =====
1.000 0.620
2.000 1.240
3.000 1.860
Is the problem that your table ends without putting out a value for 3.2? A simple way to solve that (only using loop statements, per your requirement) would be to add the following code:
while (count < km)
{
printf ("%8.3lf %14.3lf\n", km, KM_TO_MILE * km);
count = km;
}
It's really an if statement in disguise, and I don't know if your prof would accept it, but it does provide the final line of output.
Are you required to put out entries that increase by 1.0 (km) for each line? If not, perhaps a better solution is to determine an offset from one line to the next which lets you iterate between 1.0 and km, over a finite number of rows.
A simple solution is multiplying the input (km) by 10, 100 or 1000. Then dividing the result (mi) by the same constant. But avoid printing the result in the loop, take it out of there.
You may lose precision, though (that's your next exercise :)
#include <stdio.h>
#define KM_TO_MILE .62
#define NAMEITHOWYOULIKE 100.0
main (void)
{
double km, mi, count;
printf ("This program converts kilometers to miles.\n");
do
{
printf ("\nEnter a positive non-zero number");
printf (" of kilometers of the race: ");
scanf ("%lf", &km);
getchar();
}while (km <= 1);
km = km * NAMEITHOWYOULIKE;
printf ("\n KILOMETERS MILES (while loop)\n");
printf (" ========== =====\n");
count = 1;
while (count <= km)
{
mi = KM_TO_MILE * count;
++count;
}
printf ("%8.3lf %14.3lf\n", count/NAMEITHOWYOULIKE, mi/NAMEITHOWYOULIKE);
getchar();
}
If you want this for output:
KILOMETERS MILES (while loop)
========== =====
1.000 0.620
2.000 1.240
3.000 1.860
3.200 1.984
Just add the following after your while loop (for an exclusive "final result"):
mi = KM_TO_MILE * km;
printf("%8.3lf %14.3lf\n", km, mi);
or an inclusive "final result" to prevent the last two results being the same if a whole number is used:
while (km > count)
{
mi = KM_TO_MILE * km;
printf("%8.3lf %14.3lf\n", km, mi);
break;
}
You successfully printed the whole number values, but need to print the final value when that is complete. All you need to do at the end (above) is convert the value directly from kilometers to miles.
output image
#include<stdio.h>
int main() {
double kilo, miles, i;
printf("enter the kilometer to be converted :");
scanf("%lf",&kilo);
printf("kilos\t miles\n");
printf("-----------------------------------------------------\n");
i=1;
while(i<=kilo){
miles=i/1.609;
printf("%lf\t %lf\n",i,miles);
i++;
}
}