Java 程序计算复利


2022年12月28日, Learn eTutorial
1647

要编写一个 Java 程序来计算复利,我们必须从用户那里读取本金年利率时间周期计息次数

我们如何计算复利?

我们可以使用以下公式计算复利:

CI = P (1 + R/n) (nt) - P

其中,

  • P 是本金。
  • R 是年利率。
  • t 是时间周期
  • n 是在时间 t 内计息的次数。

如何在 Java 中读取 double 值?

要读取 double 值,我们可以使用 Java Scanner 类中的 nextDouble() 函数。在此程序中,我们必须将本金、利率、时间读取为 double。因此,我们必须编写如下代码:

          System.out.print("请输入本金:");
          p = sc.nextDouble();

如何使用 Java 程序计算复利?

首先,我们必须声明类 CInterest。然后打开主函数。然后声明变量 'p, r, t, ci' 为 double 类型,'n' 为整数类型。从用户那里将本金读取到变量 'p' 中。将年利率读取到变量 'r' 中。从用户那里将时间周期读取到变量 't' 中。将计息次数读取到变量 'n' 中。然后计算复利为 ci = p * Math.pow(1 + (r / n), n * t)。然后使用 system.out.println() 函数显示复利为 'ci'。

 

算法

步骤 1:声明带有 public 修饰符的类 CInterest。

步骤 2:打开**main()**函数以启动程序,Java程序的执行从**main()**开始

步骤 3:声明变量 prtci 为 double 类型,n 为整数类型。

步骤 4:从用户那里将本金读取到变量 p 中。

步骤 5:将利率读取到变量 r 中。

步骤 6:将时间周期读取到变量 t 中。

步骤 7:将计息次数读取到变量 n 中。

步骤 8:计算复利为 p * Math.pow(1 + (r / n), n * t)

步骤 9:显示复利。

Java 源代码

                                          import java.util.Scanner;
public class CInterest
{
    public static void main(String args[]) 
    {
        double p,r,t,ci;
        int n;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the Principal amount : ");
        p = sc.nextDouble();//Read Principal amount
        System.out.print("Enter the Rate of interest  : ");
        r = sc.nextDouble();//Read rate of interset
       System.out.print("Enter the number of times the interest is compounded : ");
        n = sc.nextInt();//Read n
        System.out.print("Enter the Time period : ");
        t = sc.nextDouble();//Read the time period
       sc.close();
        ci =  p * Math.pow(1 + (r / n), n * t);
        System.out.print("Compound Interest is: " +ci);
    }
}
                                      

输出

OUTPUT 1

Enter the Principal amount :2000
Enter the Rate of interest per year : 0.08
Enter the number of times the interest is compounded :12
Enter the time period in year : 5
Compound Interest is:2979.69141660321