0

I'm quite new to programming and I can't get a function to calculate properly. It is a compound interest calculator that uses this formula:

I = P ( 1 + i )n — P (p= principal i= interest n= years) Rate := to interest value.

On pascal my function looks like this,

function Compoundinterest(principal, years: integer; rate: double): double;

var
divrate: double;
interest: Double;


begin

divrate := rate/100;
interest := principal * power(1 + divrate, years) - Principal;
result := interest; 

end;

It compiles fine but just wont return the right value.

for example 1000 principal, 15% interest over 3 years returns this : 1.52087500000000E+000.

I assume I'm doing something wrong in the formula?

Thanks for your help in advance.

user3932000
  • 671
  • 8
  • 24
Roe
  • 1
  • 1

3 Answers3

1

In pascal, a function returns what it's name has been set to within the function. For example:

function set_one(): integer;

begin
   set_one := 1
end;

In your function, you should replace

result := interest; 

with

Compoundinterest := interest;

or to show in completion (with a few changes):

function compound_interest(principal, years: integer; rate: double): double;
var
   divrate: double;

begin
   divrate := rate / 100.0;
   compound_interest := principal * power(1 + divrate, years) - principal;
end;

However, this assumes that you have access to the power function. In order to access the power function, the program must have: uses math written under the program header. This code was tested on compiles on Free Pascal Compiler version 2.6.4.

For more info on Pascal, see: https://www.tutorialspoint.com/pascal/pascal_functions.htm

For an online Pascal terminal, see: https://www.tutorialspoint.com/compile_pascal_online.php

mjsyp
  • 11
  • 4
0

I tested here with Free Pascal 3.0.0 and it works (5.20875. I added

 {$mode delphi}
 uses math; 

before your code and

begin
 writeln(compoundinterest(1000,3,15));
end.

after. Verify that you do this too, or explain more about which pascal system you use.

If this is only a first step in some calculation you might also be interested in the math unit financial functions

Marco van de Voort
  • 25,628
  • 5
  • 56
  • 89
0

You have to set the format of decimal using :0:2

Try this

result := interest:0:2;

Counting the number of decimal places in pascal

var
divrate: double;
interest: Double;


begin

divrate := rate/100;
interest := principal * power(1 + divrate, years) - Principal;
result := interest:0:2; 

end;
Community
  • 1
  • 1
Metris Sovian
  • 254
  • 4
  • 20