Java簡單利息計算程式


本文旨在編寫一個Java程式來計算簡單利息。但在用程式設計方法實現之前,讓我們先了解一下如何用數學方法計算簡單利息。簡單利息是一種確定在特定利率下,在給定時間段內本金所獲得的利息金額的技術。與複利不同,它的本金不會隨時間推移而改變。

計算簡單利息,我們使用以下公式:

Simple Interest (S.I) = Principal * Time * Rate / 100

下面是相同的演示:

輸入

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

輸出

Simple Interest : 1000

在Java中計算簡單利息

我們將使用以下方法在Java中計算簡單利息:

  • 從使用者處獲取運算元的輸入

  • 在宣告時初始化值

讓我們逐一討論它們。

從使用者處獲取運算元的輸入

要從鍵盤獲取輸入,我們需要建立一個Scanner類的例項,該例項提供各種內建方法用於使用者輸入。例如,如果我們需要輸入一個雙精度值,可以使用'nextDouble()'方法。

語法

Scanner nameOfinstance = new Scanner(System.in);

示例

在下面的示例中,我們將使用Scanner類從鍵盤接受本金、利率和期限,以計算簡單利息。

import java.util.Scanner;
public class SimpleInterest {
   public static void main (String args[]) {
      // declaring principal, rate and time  
      double principal, rate, time, simple_interest;
      // Scanner to take input from user
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("Enter a Principal amount : ");
      // to take input of principle
      principal = my_scanner.nextDouble();
      System.out.println("Enter an Interest rate : ");
      // to take input of rate
      rate = my_scanner.nextDouble();
      System.out.println("Enter a Time period in years : ");
      // to take input of time
      time = my_scanner.nextDouble();
      // calculating interest
      simple_interest = (principal * rate * time) / 100;
      // to print the result
      System.out.println("The Simple Interest is : " + simple_interest);
      double totalSum = simple_interest + principal;
      System.out.println("Your total sum after gaining interest : " + totalSum);
   }
}

輸出

Enter a Principal amount : 
50000
Enter an Interest rate : 
5
Enter a Time period in years : 
2
The Simple Interest is : 5000.0
Your total sum after gaining interest : 55000.0

在宣告時初始化值

這是計算簡單利息最簡單的方法。我們只需要宣告本金、利率和期限作為運算元,並用我們選擇的值初始化它們。此外,我們還需要另一個變數來儲存簡單利息的結果。

示例

下面的示例說明了我們上面討論內容的實際實現。

public class SimpleInterest {
   public static void main (String args[]) {
      // declaring and initializing principal, rate and time  
      double principal = 50000;
      double rate = 5;
      double time = 2;
      // calculating interest
      double simple_interest = (principal * rate * time) / 100;
      // to print the result
      System.out.println("The Simple Interest is : " + simple_interest);
      double totalSum = simple_interest + principal; 
      System.out.println("Your total sum after gaining interest : " + totalSum);
   }
}

輸出

The Simple Interest is : 5000.0
Your total sum after gaining interest : 55000.0

結論

在我們的日常生活中,我們可以看到簡單利息的許多應用,例如貸款、EMI和FD。因此,學習如何用數學方法和程式設計方法計算簡單利息是必要的。在本文中,我們解釋瞭如何編寫一個Java程式來計算簡單利息。

更新於:2023年8月10日

3K+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.