3

我很新。提前为我的编码道歉。我需要打印一个显示年份的表格,然后是一个制表符,然后是下一行的值。该值必须为十进制形式。我一直在阅读、搜索和混合我的代码。我发现它适用于 1 个变量,但不是同一行中的两个。我尝试了 printf,我尝试了好的 ol 100 / 100.0,我要么得到错误,要么小数点永远不会到 2 位。我不需要它四舍五入,只是后面有 2 个空格。我显然在某个地方出错了。我将不胜感激任何帮助。导入 java.util.Scanner;

public class Investment1 {

public static double futureInvestmentValue(double investmentAmount, double monthlyInterestRate, int years){

double principal = 0.0;
double futureInvestmentValue = 0;
for (years = 1; years <=30; years++){
    //calculate futureInvestmentValue
    futureInvestmentValue = (investmentAmount * (Math.pow (1 + monthlyInterestRate, years * 12)));
    System.out.print(years + "\t" + futureInvestmentValue + "\n");

}//end for
    return futureInvestmentValue;
}//end futureInvestmentValue

public static void main(String[] args){

    Scanner input = new Scanner (System.in);

    //obtain Investment amount
    System.out.print("Enter Investment amount: ");
    double investmentAmount = input.nextDouble();

    //obtain monthly interest rate in percentage
    System.out.print("Enter annual interest rate in percentage: ");
    double annualInterestRate = input.nextDouble();
    double monthlyInterestRate = (annualInterestRate / 1200);

int years = 30;

System.out.println("Years\t" + "Future Value");
System.out.print(years + "\t");
System.out.print(years + "\t" + ((int)(futureInvestmentValue(investmentAmount, monthlyInterestRate, years))) + "\n");

}//end main
}//end Investment
4

2 回答 2

1

您可以使用system.out.format()

System.out.format("%d \t %.2f", years, futureInvestmentValue);
于 2013-02-26T16:39:41.553 回答
0

您应该阅读有关格式字符串的信息,这是一个简单的用法示例:

System.out.println(String.format("%d %.2f",myint,myfloat));

myint%d由于在格式字符串中使用了,将打印为整数(即​​使它是浮点值) 。由于格式字符串中
myfloat的部分,将打印为小数点后 2 位的十进制数。%f.2

于 2013-02-26T16:36:16.160 回答