Java程序计算简单利息和复合利息
要理解此示例,您应该具备以下 Java 编程 主题的知识:
示例 1:用 Java 计算简单利息
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// 创建 Scanner 类的对象
Scanner input = new Scanner(System.in);
// 从用户那里获取输入
System.out.print("输入本金:");
double principal = input.nextDouble();
System.out.print("输入利率:");
double rate = input.nextDouble();
System.out.print("输入时间:");
double time = input.nextDouble();
double interest = (principal * time * rate) / 100;
System.out.println("本金:" + principal);
System.out.println("利率:" + rate);
System.out.println("时间长度:" + time);
System.out.println("简单利息:" + interest);
input.close();
}
}
输出
输入本金:1000
输入利率:8
输入时间:2
本金:1000.0
利率:8.0
时间长度:2.0
简单利息:160.0
在上述示例中,我们使用了 Scanner
类从用户那里获取 本金、利率 和 时间 作为输入。然后我们使用简单利息的公式来计算简单利息。
简单利息 = (本金 * 利率 * 时间) / 100
示例 2:计算复合利息
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// 创建 Scanner 类的对象
Scanner input = new Scanner(System.in);
// 从用户那里获取输入
System.out.print("输入本金:");
double principal = input.nextDouble();
System.out.print("输入利率:");
double rate = input.nextDouble();
System.out.print("输入时间:");
double time = input.nextDouble();
System.out.print("输入利息复合次数:");
int number = input.nextInt();
double interest = principal * (Math.pow((1 + rate/100), (time * number))) - principal;
System.out.println("本金:" + principal);
System.out.println("利率:" + rate);
System.out.println("时间长度:" + time);
System.out.println("利息复合次数:" + number);
System.out.println("复合利息:" + interest);
input.close();
}
}
输出
输入本金:1000
输入利率:10
输入时间:3
输入利息复合次数:1
本金:1000.0
利率:10.0
时间长度:3.0
利息复合次数:1
复合利息:331.00000000000045
在上述示例中,我们使用了复合利息公式来计算复合利息。
这里,我们使用了 Math.pow() 方法来计算数字的幂。