📜  Java程序来计算单利和复利

📅  最后修改于: 2020-09-26 19:17:50             🧑  作者: Mango

在此示例中,我们将学习计算Java中的单利和复利。

示例1:计算Java的简单兴趣
import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    // create an object of Scanner class
    Scanner input = new Scanner(System.in);

    // take input from users
    System.out.print("Enter the principal: ");
    double principal = input.nextDouble();

    System.out.print("Enter the rate: ");
    double rate = input.nextDouble();
    rate = rate/100;

    System.out.print("Enter the time: ");
    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 Duration: " + time);
    System.out.println("Simple Interest: " + interest);

    input.close();
  }
}

输出

Enter the principal: 1000
Enter the rate: 8
Enter the time: 2
Principal: 1000.0
Interest Rate: 8.0
Time Duration: 2.0
Simple Interest: 160.0

在上面的示例中,我们使用Scanner类从用户输入principalratetime作为输入。然后,我们使用简单兴趣公式来计算简单兴趣。

Simple Interest = (Principal * Rate * Time) / 100

示例2:计算复利
import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    // create an object of Scanner class
    Scanner input = new Scanner(System.in);

    // take input from users
    System.out.print("Enter the principal: ");
    double principal = input.nextDouble();

    System.out.print("Enter the rate: ");
    double rate = input.nextDouble();

    System.out.print("Enter the time: ");
    double time = input.nextDouble();

    System.out.print("Enter number of times interest is compounded: ");
    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 Duration: " + time);
    System.out.println("Number of Time interest Compounded: " + number);
    System.out.println("Compound Interest: " + interest);

    input.close();
  }
}

输出

Enter the principal: 1000
Enter the rate: 10
Enter the time: 3
Enter number of times interest is compounded: 1
Principal: 1000.0
Interest Rate: 10.0
Time Duration: 3.0
Number of Time interest Compounded: 1
Compound Interest: 331.00000000000045

在上面的示例中,我们使用了复利的公式来计算复利。

在这里,我们使用了Math.pow()方法来计算数字的幂。