Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java คำนวณดอกเบี้ยทบต้น (Compound Interest)

ในบทความนี้ เราจะเรียนรู้วิธีคำนวณดอกเบี้ยทบต้นในภาษา Java

สูตร

Compound Interest = P × (1 + R/100)^T - P

โดย P = Principal (เงินต้น), R = Rate (อัตราดอกเบี้ย%), T = Time (ปี)

ตัวอย่างการทำงาน

อินพุต:

Principle: 100000
Interest rate: 5
Time period: 3 years

เอาต์พุต:

The Compound Interest is: 15762.50000000001

อัลกอริทึม

  1. เริ่มต้นโปรแกรม
  2. ประกาศตัวแปร double: principle, rate, time, compound_interest
  3. รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
  4. คำนวณ: compound_interest = principle * Math.pow((1 + rate/100), time) - principle
  5. แสดงผลลัพธ์
  6. จบโปรแกรม

ตัวอย่างที่ 1: รับค่าจากผู้ใช้

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);
    }
}

ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า

public class CompoundInterest {
    public static void main(String args[]) {
        double principle = 100000, rate = 5, time = 3, compound_interest;

        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);
    }
}

หมายเหตุ

  • ใช้ Math.pow(base, exponent) สำหรับการยกกำลัง
  • ดอกเบี้ยทบต้นให้ผลตอบแทนสูงกว่าดอกเบี้ยธรรมดา เพราะคำนวณดอกเบี้ยจากดอกเบี้ยที่สะสม
  • ตัวแปรควรเป็น double เพื่อความแม่นยำ