English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在此示例中,我们将学习Java中的计算单利和复利。
要理解此示例,您应该了解以下Java编程主题:
import java.util.Scanner; class Main { public static void main(String[] args) { //创建一个Scanner类的对象 Scanner input = new Scanner(System.in); //接受用户的输入 System.out.print("输入本金: \u00A0"); double principal = input.nextDouble(); System.out.print("输入利率: \u00A0"); double rate = input.nextDouble(); rate = rate/100; System.out.print("输入时间: \u00A0"); double time = input.nextDouble(); double interest = (principal * time * rate) / 100; System.out.println("Principal: " + principal); System.out.println("Interest rate: " + rate); System.out.println("Time: " + time); System.out.println("单利: \u00A0" + interest); input.close(); } }
Output result
Enter the principal: 1000 Enter the interest rate: 8 Enter the time: 2 Principal: 1000.0 Interest rate: 8.0 Time: 2.0 单利: 160.0
在上面的示例中,我们使用了Scanner类来接收来自用户的输入的 principal,rate 和 time。然后,我们使用单利率公式来计算单利。
单利 = (Principal * Rate * Time) / 100
import java.util.Scanner; class Main { public static void main(String[] args) { //创建一个Scanner类的对象 Scanner input = new Scanner(System.in); //接受用户的输入 System.out.print("输入本金: \u00A0"); double principal = input.nextDouble(); System.out.print("输入利率: \u00A0"); double rate = input.nextDouble(); System.out.print("输入时间: \u00A0"); double time = input.nextDouble(); System.out.print("输入复利次数: \u00A0"); int number = input.nextInt(); double interest = principal * (Math.pow((1 + rate/100), (time * number))) - principal; System.out.println("Principal: " + principal); System.out.println("Interest rate: " + rate); System.out.println("Time: " + time); System.out.println("Number of compound interest periods: " + number); System.out.println("Compound interest: " + interest); input.close(); } }
Output result
Enter the principal: 1000 Enter the interest rate: 10 Enter the time: 3 Enter the number of compound interest periods: 1 Principal: 1000.0 Interest rate: 10.0 Time: 3.0 Number of compound interest periods: 1 Compound interest: 331.00000000000045
In the above example, we use the compound interest formula to calculate compound interest.
Here, we useMath.pow()A method to calculate the power of a number.