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

โปรแกรม Java คำนวณดอกเบี้ยธรรมดาและดอกเบี้ยทบต้น

ในบทความนี้ เราจะเรียนรู้วิธีคำนวณดอกเบี้ยธรรมดา (Simple Interest) และดอกเบี้ยทบต้น (Compound Interest) ในภาษา Java

สูตรการคำนวณ

  • ดอกเบี้ยธรรมดา (SI): (P × R × T) / 100
  • ดอกเบี้ยทบต้น (CI): P × (1 + R/100)^T - P

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

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

อินพุต:

Principal = 25000.0
Annual Rate of Interest = 10.0
Time (years) = 4.0

เอาต์พุต:

Simple Interest: 10000.0
Compound Interest: 11602.500000000007

อัลกอริทึม

  1. เริ่มต้นโปรแกรม
  2. ประกาศตัวแปร double: p, r, t, s_interest, c_interest
  3. รับค่า p, r, t จากผู้ใช้
  4. คำนวณ SI = (p * r * t) / 100
  5. คำนวณ CI = p * Math.pow(1.0 + r/100.0, t) - p
  6. เก็บผลลัพธ์และแสดง
  7. จบโปรแกรม

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

import java.util.*;

public class SimpleAndCompoundInterest {
    public static void main(String[] args) {
        double p, r, t, s_interest, c_interest;
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter the value of Principal = ");
        p = scanner.nextDouble();
        System.out.println("Enter the Annual Rate of Interest = ");
        r = scanner.nextDouble();
        System.out.println("Enter the Time (years) = ");
        t = scanner.nextDouble();

        s_interest = (p * r * t) / 100;
        c_interest = p * Math.pow(1.0 + r / 100.0, t) - p;

        System.out.println("Simple Interest: " + s_interest);
        System.out.println("Compound Interest: " + c_interest);
    }
}

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

import java.util.*;

public class SimpleAndCompoundInterest {
    public static void main(String[] args) {
        double p = 25000, r = 10, t = 4, s_interest, c_interest;

        System.out.println("Principal = " + p);
        System.out.println("Annual Rate of Interest = " + r);
        System.out.println("Time (years) = " + t);

        s_interest = (p * r * t) / 100;
        c_interest = p * Math.pow(1.0 + r / 100.0, t) - p;

        System.out.println("Simple Interest: " + s_interest);
        System.out.println("Compound Interest: " + c_interest);
    }
}

ดอกเบี้ยทบต้นให้ผลตอบแทนสูงกว่าดอกเบี้ยธรรมดา เพราะคำนวณจากเงินต้นรวมดอกเบี้ยที่สะสม