正确格式

ma8fv8wu  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(410)

我有工作的程序,我只是需要帮助切断额外的数字,我不太善于使用printf语句时,在java打印。当我运行它时,我得到了类似1225.043的输出:

import java.util.Scanner;

public class Comparison {

    public static void main(String[] args) 
    {
        Scanner keyboard = new Scanner(System.in);

        float amount;
        double principal = 1000.00;
        double rate;

        System.out.println("Enter interest rate");
        rate = keyboard.nextDouble();

        System.out.println("Year" +"     "+ "Amount on deposit");

        for(int year = 1; year <= 10; ++year)
        {
            amount = (float) (principal * Math.pow(1.0 + rate, year));

            System.out.println(year+ "       "+ amount);
            System.out.println();
        }
    }
}
ff29svar

ff29svar1#

尝试

System.out.printf("%2d       %.2f%n", year, amount);

输出:

Enter interest rate
0.1
Year     Amount on deposit
 1       1100.00
 2       1210.00
 3       1331.00
 4       1464.10
 5       1610.51
 6       1771.56
 7       1948.72
 8       2143.59
 9       2357.95
10       2593.74

相关问题