My C program has to contain a loop that increases the interest rate, and a nested loop that calculates the interest and displays a total per each interest rate. Can anyone point me in the right direction?
The program should output 10 interest rates and the corresponding total interest plus the loan
The interest rate starts .01 (1 percent) and should end at .10 (10 percent).
#include <stdio.h>
int main(void)
{
double loan = 1000.00, rate = 0.01, output;
int year = 1;
do {
rate + 0.01;
for (year = 1; year < 11; year++) {
output = rate * loan + loan;
}
printf("%d $%d\n", year, output);
} while (year < 11);
return 0;
}
First things first, turn on warnings. C compilers normally don't give you warnings, it's generally -Wall to get the basics (not all). Once we do that...
test.c:17:36: warning: format specifies type 'int' but the argument has type 'double' [-Wformat]
printf("%d $%d\n", year, output);
~~ ^~~~~~
%f
That tells us you're passing a floating point number to printf but trying to treat it as an integer, so it's going to be translated to a string incorrectly. It needs to be.
printf("%d $%.2f\n", year, output);
%f for a floating point number, and the .2 means to only use two decimal places like money.
test.c:9:14: warning: expression result unused [-Wunused-value]
rate + 0.01;
~~~~ ^ ~~~~
2 warnings generated.
This one tells us that the rate is never incremented. It's added to, but never stored anywhere. Instead you want rate += 0.01.
Now it runs. Once. And it only reports on year 11.
The problem is your outer do/while loop is using year, but the for loop will end with the year at the threshhold, so it will immediately stop. Instead of using a do/while loop, which is rarely necessary, use another for loop.
Second problem is you're printing the output and year outside the year for loop. So you'll only ever get the result for the last year. If you want all the years, the print goes inside.
#include <stdio.h>
int main(void)
{
const double initial_loan = 1000.00;
for( double rate = 0.01; rate <= 0.10; rate += 0.01 ) {
double loan = initial_loan;
for (int year = 1; year <= 10; year++) {
loan += rate*loan;
printf("%d # %.2f%% $%.2f\n", year, rate * 100, loan);
}
}
return 0;
}
Notice that I declare variables in the narrowest possible scope. This tells you when they're appropriate to be used, and avoids goofs like trying to use the year in the outer loop.
A lot of C material will be extremely conservative and tell you to declare all variables at the start of a function. This isn't necessary, and hasn't been for a long, long time. Though declaring variables in a for loop is a C99 thing, that part of C99 is very well supported.
Related
#include <stdio.h>
int main(){
double km, miles, yards, feet, inches;
scanf("%lf", &km);
miles = km/1.609;
printf("%d\n", (int)miles);
yards = ((km*1093.61) - ((int)miles*1760));
printf("%d\n", (int)yards);
feet = (km*3281.4) - ((int)miles*5280 + yards*3);
printf("%d\n", (int)feet);
inches = km*39378.498 - ((int)miles*63360 + (int)yards*36 + (int)feet*12);
printf("%.2lf", inches);
return 0;
}
This is what I managed to write, however it still doesn't pass all tests and isn't 100% accurate as seen in the image below
Help would be highly appreciated.
When writing code to do conversions such as in your task, it is better to do all (internal) calculations in double precision and convert each component part of the result (to int) 'on the fly', then subtract each of those converted values as they are determined.
So, first get the conversion into miles as a double value, then subtract each integral part and multiply the remainder by the factor required to get the next sub-unit. Using this approach, you are far less likely to encounter problems due to integer overflow and rounding errors.
The following is a potential solution. (Note that it is far better to write clear code than attempt to 'compress' many operations into single-line code; the latter is a common cause for bugs creeping into your code and also makes it more difficult for future developers of your code to understand and/or modify it.)
#include <stdio.h>
int main()
{
double km = -1.0, total, inches;
int miles, yards, feet;
do {
printf("Enter value in Km: ");
if (scanf("%lf", &km) != 1) { // Error input: clear buffer
int c;
while ((c = getchar()) != '\n' && c != EOF)
;
if (c == EOF) return 1; // Can't do much after an EOF!
}
} while (km < 0.0);
// First, do the conversion to double "total" ...
total = km / 1.609;
// Now, get the integer "miles" value and subtract that from the total ...
miles = (int)total;
total -= (double)miles;
// Next, multiply remainder by 1760 to get the number of yards ...
total *= 1760.0;
// Now, get the integer value and subtract that from total ...
yards = (int)total;
total -= (double)yards;
// Multiply remainder by 3 to get feet ...
total *= 3.0;
feet = (int)total;
total -= (double)feet;
// Finally, multiply remainder by 12 to get inches ...
inches = total * 12.0;
// Display result:
printf("%d %d %d %.2lf\n", miles, yards, feet, inches);
return 0;
}
Note that I have also added some code to check that the input value is 'acceptable' (I have chosen to reject negative values, but you can easily change that condition); more importantly, the code will also be able to deal with situations where the user enters a value that cannot be interpreted as a floating-point input (like "Fred"). When using scanf for user input, it is always a good idea to check for valid input and handle possible error conditions.
Edit:I solved the issue by first multiplying the float value by 100, then rounding it with roundf() function, then casting it to an integer to be stored in an integer variable. I did the remaining operations with integer values from there on and everything worked. Even though the solution offered by #JacobBoertjes actually worked, my assignment requiered me to use get_float() from the cs50.h library, so I didn't implement it. Here's the final code:
// Get user input as a positive float value
float f_change;
do {
printf("Change owed: ");
f_change = get_float();
} while(f_change < 0);
// Round & cast
int int_change = (int) roundf(f_change * 100);
My program accepts an amount of money, say $4.20, and figures out the least amount of coins with which it can represent this value. For example, desired output from the program with $4.20 as an input would be: 16 quarters ($4.00), 2 dimes ($0.20).My program successfully calculates the number of quarters, but fails to do so while working on dimes. The cause of this failure is the second for loop in the code. 0.10 >= 0.10 does not evaluate to true, so the last iteration of the loop never happens. What am I doing wrong? Here is the code. I provided test print statements with their outputs written as comments.
#include <stdio.h>
#include <cs50.h>
int main(void) {
// Fake user input
float owed_coin = 4.2f;
// Initialize coin variables
int coin_count = 0;
float quarters = 0.25f,
dimes = 0.10f;
// Calculate quarters
while(owed_coin >= quarters) {
owed_coin -= quarters;
coin_count += 1;
}
printf("owed_coin: %.2f\ncoin_count: %d\n\n", owed_coin, coin_count);
// Prints owed_coin: 0.20
// coin_count: 16
// Calculate dimes
while(owed_coin >= dimes) {
owed_coin -= dimes;
coin_count += 1;
}
printf("owed_coin: %.2f\ncoin_count: %d\n\n", owed_coin, coin_count);
// Prints owed_coin: 0.10
// coin_count: 17
}
Floating point comparison is generally a bad idea because floats often become non-exact and thus will not be exactly equal. As #bruceg mentioned, a good solution is to keep your monetary values in terms of cents, so that you avoid using a float.
You could replace float owed_coin = 4.2f; with int owed_coin = 420;
In terms of gathering user input into this number, here is my suggestion using scanf
int n1, n2;
printf("Please enter amount:");
scanf("%d.%2d", &n1, &n2);
owed_coin = n1*100 + n2;
Another solution allows you you keep your variables as floats, and just compare for a very small difference between the two. It can be found here: What's wrong with using == to compare floats in Java?
It uses the Java Math library, but a similar solution could look something like this in C:
while((owed_coin - dimes) >= -0.001) {
owed_coin -= dimes;
coin_count += 1;
}
If you want to learn more about why floating point numbers suffer small innacuracies then check this out: https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems
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.
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" ;)
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++;
}
}