Java 計算複利程式


在本文中,我們將瞭解如何在Java中計算複利。複利使用以下公式計算:

Principle*(1+(rate / 100))^time – Principle

複利 - 對本金和累計利息收取的百分比利息。利率比單利高。

我們將探討如何獲取本金**金額**、**利率**和**期限**的使用者輸入,然後根據提供的公式計算複利。最後,您將瞭解如何在 Java 中針對**使用者定義**值和**預定義**值實現此公式。

問題陳述

編寫一個 Java 程式,使用公式計算複利。以下是演示:

輸入

Enter a Principle number : 100000
Enter Interest rate : 5
Enter a Time period in years : 3

輸出

The Compound Interest is : 15762.50000000001

不同的方法

以下是計算複利的不同方法:

對於使用者自定義輸入

以下是使用使用者自定義輸入計算複利的步驟:

  • 使用來自java.util 包Scanner 類匯入所需的包。
  • 定義一個用於捕獲使用者輸入的掃描器物件。
  • 提示使用者輸入以獲取本金金額、利率和期限。
  • 使用公式根據使用者輸入計算**複利**。
  • 顯示計算出的複利。

示例

在這裡,輸入是根據提示由使用者輸入的。您可以在我們的程式碼執行工具 執行按鈕中即時嘗試此示例。

import java.util.Scanner;
public class CompoundInterest {
   public static void main (String args[]){
      double principle, rate, time, compound_interest;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A Scanner object has been defined ");
      System.out.print("Enter a Principle number : ");
      principle = my_scanner.nextInt();
      System.out.print("Enter Interest rate : ");
      rate = my_scanner.nextInt();
      System.out.print("Enter a Time period in years : ");
      time = my_scanner.nextInt();
      compound_interest = principle * (Math.pow((1 + rate / 100), time)) - principle;
      System.out.println("The Compound Interest is : " + compound_interest);
   }
}

輸出

Required packages have been imported
A Scanner object has been defined
Enter a Principle number : 100000
Enter Interest rate : 5
Enter a Time period in years : 3
The Compound Interest is : 15762.500000000015

對於預定義值

以下是使用預定義值計算複利的步驟:

  • 透過重新定義**本金**、**利率**和**期限**的值來初始化變數。
  • 顯示預定義的本金金額、利率和期限。
  • 使用公式中預定義的值計算複利。
  • 顯示計算出的複利。

在這裡,整數已預先定義,其值將在控制檯上訪問和顯示。

public class CompoundInterest{
 public static void main (String args[]){
  double principle, rate, time, compound_interest;
principle = 100000;
      rate = 5;
      time = 3;
      System.out.printf("The Principle amount is %f \nThe interest rate is %f \nThe time period in years is %f " , principle, rate, time);
      compound_interest = principle * (Math.pow((1 + rate / 100), time)) - principle;
      System.out.println("\nThe Compound Interest is: " + compound_interest);
   }
}

輸出

The Principle amount is 100000.000000
The interest rate is 5.000000
The time period in years is 3.000000
The Compound Interest is: 15762.50000000001

更新於:2024年9月2日

15K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告