Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java tính lãi kép


Trong bài viết này, chúng ta sẽ tìm hiểu cách tính lãi kép trong Java. Lãi kép được tính bằng công thức:

Gốc * (1 + (lãi suất / 100))^thời gian - Gốc

Lãi kép – Phần trăm lãi tính trên cả gốc và lãi đã tích lũy. Lãi suất cao hơn lãi đơn.

Dưới đây là minh họa:

Đầu vào

Giả sử đầu vào:

Nhập số tiền gốc: 100000
Nhập lãi suất: 5
Nhập thời gian (năm): 3

Đầu ra

Kết quả mong đợi:

Lãi kép là: 15762.50000000001

Thuật toán

Bước 1 – BẮT ĐẦU
Bước 2 – Khai báo 4 biến double: principle, rate, time, compound_interest
Bước 3 – Đọc giá trị principle, rate, time từ người dùng
Bước 4 – Thực hiện: principle * (Math.pow((1 + rate / 100), time)) - principle để tính lãi kép, lưu vào compound_interest
Bước 5 - Hiển thị compound_interest
Bước 6 – DỪNG

Ví dụ 1: Nhập từ bàn phím

Người dùng nhập dựa trên lời nhắc. Thử trực tiếp trong coding ground.

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

Đầu ra

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

Ví dụ 2: Giá trị định nghĩa trước

Các giá trị đã được định nghĩa trước.

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

Đầu ra

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