What is wrong with the following code? - c

//A program that calculates the amount of money in a bank account after n years
#include <stdio.h>
double bank(double money, double apy, int years);
int main() {
double money1, apy1;
int years1;
printf("How much money is currently in your bank account? ");
scanf("%d", &money1);
printf("How many years will this money stay in your account? ");
scanf("%d",&years1);
printf("What is your APY? ");
scanf("%d", &apy1);
int bank1 = bank(money1, apy1, years1);
printf("Your grand total after %d will be $%d \n", years1, bank1);
system ("PAUSE");
return 0;
}
double bank(double money, double apy, int years) {
if(years <= 0)
return money;
else
return bank(money*apy, apy, years-1);
}

Change:
scanf("%d", &money1);
to
scanf("%lf", &money1);
and change:
scanf("%d", &apy1);
to:
scanf("%lf", &apy1);
And while you're at it you might want to add some printfs to help with debugging (assuming you don't have a source level debugger.)

This:
return bank(money*apy, apy, years-1);
should probably be
return bank(money*(1+apy), apy, years-1);
since the interest you earn should be added to the existing amount. Otherwise your total amount would be reducing each year.

Another one is :
double bank(double money, double apy, int years);
Returns a double, but
int bank1 = bank(money1, apy1, years1);
You place the result in an int.

You should never use floating point in financial calculations.
Floating point is inherently uncapable of representing 10-base values precisely, which means that you will suffer from rounding errors and unequalities, which is unacceptable in finances (among others).
This has been discussed in detail many times on SO. The issue is not language specific.

I think you should call you function in the following way:
int bank1 = bank(money1, 1+apy1/100., years1);
Otherwise you'll have a LOT of money :)

Related

How to get the total?

Good day, I am practicing about Arithmetic and started to experiment a bit and got confused. How can I total the liter, refueled, and tendered?
#include <stdio.h>
int main()
{
int liter, refueled, tendered, changed;
printf("Enter the price of the fuel per liter: ");
scanf("%f",&liter);
printf("Enter the number of liters the customer wants refueled: ");
scanf("%f",&refueled);
printf("Enter the amount tendered: ");
scanf("%f",&tendered);
printf("your change is %.2f pesos. Thank you and come again!", changed = liter * refueled - tendered);
return 0;
}
It seems like float is more appropriate for all your variables (liter, refueled, tendered, changed). There's no reason to allow only integer amounts of fuel etc. You also scanfed them using "%f" which is used for floats.
It's better to assign changed in a separate line, or alternatively get rid of it altogether and simply put the mathematical expression in the printf call.
You inverted the value of changed. Should be tendered - liter * refueled.
Better version:
#include <stdio.h>
int error_handler(/*error params*/)
{
int errCode{ 1 };
// Error handling based on the params, set errCode ...
return errCode;
}
float get_change(float liter, float refueled, float tendered)
{
return tendered - liter * refueled;
}
int main()
{
float liter{ 0 }, refueled{ 0 }, tendered{ 0 };
printf("Enter the price of the fuel per liter: ");
if (scanf("%f", &liter) != 1) {
return error_handler(/*error params*/);
}
printf("Enter the number of liters the customer wants refueled: ");
if (scanf("%f", &refueled) != 1) {
return error_handler(/*error params*/);
}
printf("Enter the amount tendered: ");
if (scanf("%f", &tendered) != 1) {
return error_handler(/*error params*/);
}
printf("your change is %.2f pesos. Thank you and come again!\n", get_change(liter, refueled, tendered));
return 0;
}
Update:
Following the comments below I updated my solution with:
Skeleton for error handling for scanf.
A separate function for the change calculation. In this case it seems a bit contrived, but it's correct from a methodical software engineering point of view (imagine this calculation getting a lot more complex in some real life scenario). Note: you can further apply this principle and extract for example the code for getting input from the user to a separate function. In my code above I decided it is enough to demonstrate it with get_change and error_handler.
Your scanning attempts, e.g. scanf("%f",&liter); uses the format specifier for float, but gives the address of an integer.
That causes undefined behaviour, which means "do not do this" for practicals (otherwise look up the term, or for fun "nasal demons").
The simplest fix (assuming you input integer values) is to switch to "%d".
If you instead switch to using float for the variable (probably necessary), you should know, for the cases of currency (e.g. tendered), that a very recommended best practice is to then convert to an integer variable which counts the smallest denomination, e.g. cents.
I took the answer of wohlstad, which was nearly perfect and added a function for your calculation...
#include <stdio.h>
fload calculation(fload tendered, fload liter, fload refueled);
int main()
{
float liter, refueled, tendered, changed;
printf("Enter the price of the fuel per liter: ");
scanf("%f", &liter);
printf("Enter the number of liters the customer wants refueled: ");
scanf("%f", &refueled);
printf("Enter the amount tendered: ");
scanf("%f", &tendered);
changed = calculation(tendered, liter, refueled);
printf("your change is %.2f pesos. Thank you and come again!", changed);
return 0;
}
fload calculation(fload tendered, fload liter, fload refueled){
fload calcVal = tendered - liter * refueled;
return calcVal;
}
Now you can edit your calculation like you need it, adding more or less things etc...

my program isn't displaying the right average,it is giving me only zeros in decimal(New to Programming)

here is the code as written in visual studio
#include <stdio.h>
void main()
{
int n,i,num,s;
float av;
printf("How Many numbers?");
scanf("%d",&n);
s=0;
for(i=1;i<=n;i++){
printf("enter number #%d : ",i);
scanf("%d", &num);
s=s+num;
}
av=s/n;
printf("The Average is %f",av);
getchar();
}
i really don't know why it isnt displaying the right average :/
The problem is here: av=s/n; you are storing the result of an integer division into a float, there will be some data loss. A simple solution: use typecasting->
av=(float)s/n;
or
av=s/(float)n;
Another alternative: make either s or n a float.
av=s/n; Lookup "integer division". You probably want to use av=(float)s/n;
Division of two integer values doesn't automatically convert to a float value, unless you use a cast.

C - Output value not calculating correctly

I'm just started to learn how to code and decided to try to create a program that would calculate the amount of calories a person burns based on certain values that are asked of them. However, whenever I run it instead of getting the calculated value based on their values I keep getting the value 2686708. I just can't seem to make it work no matter what.
//included libraries
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//constants
#define WALKING_CAL 5
#define EXERCISING_CAL 10
#define EATING_CAL 40
#define DRINKING_CAL 20
#define CALORIES_PER_POUND 3500*/
//main function
int main() {
int current_weight, goal_weight;
int walking, exercise, drinking, eating;
int total_walking, total_exercising, total_eating, total_drinking;
int calories_burned, calories_gained;
printf("What is your current weight?\n");
scanf("%d", &current_weight);
printf("\nWhat is your goal weight?\n");
scanf("%d", &goal_weight);
total_walking = WALKING_CAL * walking;
total_exercising = EXERCISING_CAL * exercise;
total_eating = EATING_CAL * eating;
total_drinking = DRINKING_CAL * drinking;
calories_burned = (total_walking + total_exercising)- (total_eating + total_drinking);
if (goal_weight > current_weight){
printf("\nHow many minutes do you walk per day?\n");
scanf("%d", &walking);
printf("\nHow many minutes do you exercise per day?\n");
scanf("%d", &exercise);
printf("\nHow many minutes do you drink per day?\n");
scanf("%d", &drinking);
printf("\nHow many minutes do you eat per day?\n");
scanf("%d", &eating);
printf("You gain %d calories per day.", &calories_burned);
}
return 0;
}
This:
printf("You gain %d calories per day.", &calories_burned);
prints the address of the variable, not the variable's value (as an int, which in turn is undefined behavior but seems to not blow up for you at least).
It should be:
printf("You gain %d calories per day.", calories_burned);
Drop the &.

Monthly payments C program

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" ;)

My beginner C code has stopped working

I am taking my first programming class this semester and I can't figure out what is going on with my program. I have to write a program that calculates the total amount of money after so many years with interest. The formula is y=p*(1+r)^n
Anyways, whenever I run my code it comes up as "_ has stopped working" and closes.
Here is my code:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main (void)
{
double p, r, n, y;
printf("Enter the interest rate>");
scanf("%lf", r);
printf("Enter the principle amount of money invested>");
scanf("%lf", p);
printf("Enter the number of years invested>");
scanf("%lf", n);
y = pow(p*(1+r),n);
printf("The total amount of money is %f.\n", y);
system("PAUSE");
return (0);
}
I have tried googling it and it seems like it might have something to do with "initializing", but I'm not sure what that means or how to do it. Any help is greatly appreciated!
First of all the scanf() function expects the adress of a variable not the variable itself, so it should be used like that scanf("%lf", &r);Try it and you will be okay
And secondly never use system("PAUSE")!!
It is platform specific (windows) and it is wrong system("pause"); - Why is it wrong?
You are learning to program in a wrong way by using system(PAUSE) and in the above link you can see why!
This code was written and tested on linux platform.
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main (void)
{
double p, r, n, y, value;
int a = 3, b = 2;
printf("Enter the interest rate>");
scanf("%lf", &r);
printf("Enter the principle amount of money invested>");
scanf("%lf", &p);
printf("Enter the number of years invested>");
scanf("%lf", &n);
value = p * (r + 1);
y = pow(value, n);
printf("The total amount of money is %f.\n", y);
//system("PAUSE");
return (0);
}
to compile this code in linux use,
gcc code.c -lm
I dont know why, I am forced to include -lm at compile time even though I am adding #include. Any one feel free to update the answer on this.
Update.
Please see this answer for why we must use -lm Undefined reference to 'pow' even though -lm is a compile flag. [C]

Resources