因此,我试图做的任务是找出委托人达到某个特定值所需的年数。比如说我从5000美元开始,我想用10%的利率/年累计15000美元。我想找到多久这是我迄今所做的投资使用简单利息公式计算Java中的投资持续时间
的持续时间
package com.company;
import java.util.Scanner;
public class InvestmentDuration {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("Initial Investment: ");
double investment = input.nextDouble();
System.out.println ("Rate as decimals: ");
double rate = input.nextDouble();
System.out.println ("Future Value: ");
double FutureValue = input.nextDouble();
double T = 0; //Initialise Duration//
double EndValue = investment * Math.pow ((1+rate), T); //Formula of Simple Interest//
while (EndValue < FutureValue) {
T += 1.0;
if (investment * Math.pow((1 + rate), T) == FutureValue);
System.out.println("The Number of years it takes to accumulate $" + FutureValue + " is " + T + " years");
}
}
输出:
The Number of years it takes to accumulate $15000.0 is 1.0 years
The Number of years it takes to accumulate $15000.0 is 2.0 years
The Number of years it takes to accumulate $15000.0 is 3.0 years
The Number of years it takes to accumulate $15000.0 is 4.0 years
The Number of years it takes to accumulate $15000.0 is 5.0 years
The Number of years it takes to accumulate $15000.0 is 6.0 years
The Number of years it takes to accumulate $15000.0 is 7.0 years
The Number of years it takes to accumulate $15000.0 is 8.0 years
The Number of years it takes to accumulate $15000.0 is 9.0 years
The Number of years it takes to accumulate $15000.0 is 10.0 years
The Number of years it takes to accumulate $15000.0 is 11.0 years
The Number of years it takes to accumulate $15000.0 is 12.0 years
我怎么只打印最后一行?
@Yusuf宁不要使用double,请使用BigDecimal!双/浮动不用于财务/计算用途。 – Alboz
[根据Java风格指南,学习如何格式化代码并命名变量。主要大括号去的地方是宗教战斗,除此之外,其他所有东西都是现成的。](https://github.com/twitter/commons/blob/master/src/java/com/twitter/common/styleguide.md ) –