【问题标题】:Issue with calculation in function函数计算问题
【发布时间】:2016-11-29 19:02:39
【问题描述】:

我对编程很陌生,无法正确计算函数。这是一个使用这个公式的复利计算器:

I = P ( 1 + i )n — P (p= 本金 i= 利息 n= 年) 利率:= 利息值。

在帕斯卡上,我的函数看起来像这样,

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;

它编译得很好,但不会返回正确的值。

例如 1000 本金,3 年 15% 的利息返回:1.52087500000000E+000。

我认为我在公式中做错了什么?

提前感谢您的帮助。

【问题讨论】:

    标签: pascal calc


    【解决方案1】:

    在 pascal 中,函数返回在函数中设置的名称。例如:

    function set_one(): integer;
    
    begin
       set_one := 1
    end;
    

    在你的函数中,你应该替换

    result := interest; 
    

    Compoundinterest := interest;
    

    或完成显示(有一些变化):

    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;
    

    但是,这假设您可以访问power 函数。为了访问power函数,程序必须在程序头下写有:uses math。此代码已在 Free Pascal Compiler 2.6.4 版上进行了编译测试。

    有关 Pascal 的更多信息,请参阅:https://www.tutorialspoint.com/pascal/pascal_functions.htm

    有关在线 Pascal 终端,请参阅: https://www.tutorialspoint.com/compile_pascal_online.php

    【讨论】:

      【解决方案2】:

      我在这里使用 Free Pascal 3.0.0 进行了测试,它可以工作(5.20875。我添加了

       {$mode delphi}
       uses math; 
      

      在你的代码之前和

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

      之后。验证您是否也这样做,或详细说明您使用的帕斯卡系统。

      如果这只是某些计算的第一步,您可能还对math unit financial functions 感兴趣

      【讨论】:

        【解决方案3】:

        您必须使用设置十进制格式 :0:2

        试试这个

        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;
        

        【讨论】:

        • 谢谢,这正是我所需要的 :)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-20
        • 1970-01-01
        相关资源
        最近更新 更多