kachilous
kachilous

Reputation: 2529

What is wrong with the following code?

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

 }

Upvotes: 0

Views: 530

Answers (5)

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116246

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.

Upvotes: 1

user418748
user418748

Reputation:

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.

Upvotes: 2

Paul R
Paul R

Reputation: 212929

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

Upvotes: 4

Elalfer
Elalfer

Reputation: 5338

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 :)

Upvotes: 0

casablanca
casablanca

Reputation: 70691

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.

Upvotes: 4

Related Questions