我是个新手。提前为我的编码道歉。我需要打印一个显示年份的表,然后打印一个选项卡,然后打印下一行的值。该值必须是十进制形式。我一直在阅读、搜索和混合我的代码。我已经为1个变量找到了它,但不为同一行中的两个变量找到它。我试过printf,我试过好的ol 100/100.0,我要么出错,要么小数永远不会到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("Yearst" + "Future Value");
System.out.print(years + "t");
System.out.print(years + "t" + ((int)(futureInvestmentValue(investmentAmount, monthlyInterestRate, years))) + "n");
}//end main
}//end Investment
您可以使用system.out.format((:
System.out.format("%d t %.2f", years, futureInvestmentValue);
您应该了解格式化字符串,下面是一个简单的用法示例:
System.out.println(String.format("%d %.2f",myint,myfloat));
由于格式字符串中使用了%d
,myint
将被打印为整数(即使它是浮点值(
由于格式字符串中有%f.2
部分,myfloat
将打印为小数点后有2位数字的十进制数字。