Java 计算简单利息
本文的目的是编写一个Java程序来计算简单利息。但在进行编程之前,让我们先来了解一下如何在数学上计算简单利息。简单利息是一种确定在给定时间段内以指定利率计算的本金金额上获得的利息金额的技术。与复利不同,它的本金金额随时间不变。
计算简单利息,我们使用以下公式 −
Simple Interest (S.I) = Principal * Time * Rate / 100
下面是相同的演示−
输入
Enter a Principle number: 100000
Enter an Interest rate: 5
Enter a Time period in years: 2
输出
Simple Interest : 1000
在Java中计算简单利息
我们将使用以下方式在Java中计算简单利息-
- 通过从用户获取操作数的输入
-
通过在声明时初始化数值
让我们逐个讨论它们。
通过从用户获取操作数的输入
要从键盘获取输入,我们需要创建Scanner类的实例,该类提供了各种用于用户输入的内置方法。例如,如果我们需要输入双精度值,可以使用’nextDouble()’方法。
语法
Scanner nameOfinstance = new Scanner(System.in);
示例
在下面的示例中,我们将使用Scanner类从键盘接收本金金额、利率和时间期限,以找到简单利息。
import java.util.Scanner;
public class SimpleInterest {
public static void main (String args[]) {
// declaring principal, rate and time
double principal, rate, time, simple_interest;
// Scanner to take input from user
Scanner my_scanner = new Scanner(System.in);
System.out.println("Enter a Principal amount : ");
// to take input of principle
principal = my_scanner.nextDouble();
System.out.println("Enter an Interest rate : ");
// to take input of rate
rate = my_scanner.nextDouble();
System.out.println("Enter a Time period in years : ");
// to take input of time
time = my_scanner.nextDouble();
// calculating interest
simple_interest = (principal * rate * time) / 100;
// to print the result
System.out.println("The Simple Interest is : " + simple_interest);
double totalSum = simple_interest + principal;
System.out.println("Your total sum after gaining interest : " + totalSum);
}
}
输出
Enter a Principal amount :
50000
Enter an Interest rate :
5
Enter a Time period in years :
2
The Simple Interest is : 5000.0
Your total sum after gaining interest : 55000.0
通过在声明时初始化值
这是计算简单利息的最简单方法。我们只需要声明本金金额、利率和时间期限作为操作数,并用我们选择的值对其进行初始化。另外,我们需要另一个变量来存储简单利息的结果。
示例
以下示例演示了我们上面讨论的实际实现。
public class SimpleInterest {
public static void main (String args[]) {
// declaring and initializing principal, rate and time
double principal = 50000;
double rate = 5;
double time = 2;
// calculating interest
double simple_interest = (principal * rate * time) / 100;
// to print the result
System.out.println("The Simple Interest is : " + simple_interest);
double totalSum = simple_interest + principal;
System.out.println("Your total sum after gaining interest : " + totalSum);
}
}
输出
The Simple Interest is : 5000.0
Your total sum after gaining interest : 55000.0
结论
在我们的日常生活中,我们可以看到许多简单利息的应用,例如贷款、等额分期付款和定期存款。因此,有必要学习如何在数学上和编程上计算它。在本文中,我们解释了如何使用Java程序计算简单利息。