gpt4 book ai didi

java - 在java中显示2位输出小数

转载 作者:行者123 更新时间:2023-12-02 04:20:16 26 4
gpt4 key购买 nike

我试图找出为什么输出小数时的 %.2f 声明在我的代码中不起作用,我检查了其他类似的问题,但我似乎找不到我收到的特定逻辑错误中的问题。当我去编译我的程序时,它编译得很好,我去运行它,一切输出都很好,直到我达到最终成本,我试图只显示带有两位小数的十进制值。

我在线程“main”中遇到异常

Java.util.illegalformatconversionexception  f! = Java.lang.string
At java.util.Formatter$formatspecifier.failconversion(Unknown Source)
At java.util.Formatter$formatspecifier.printFloat(Unknown Source)
At java.util.Formatter.format(Unknown Source)
At java.io.printstream.format(Unknown Source)
At java.io.printstream.printf(Unknown Source)
At Cars.main(Cars.java:27)

这是我的代码:

import java.util.Scanner;
public class Cars
{

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

int carYear, currentYear, carAge;

double costOfCar, salesTaxRate;
double totalCost;

String carModel;
System.out.println("Please enter your favorite car model.");
carModel = input.nextLine();
System.out.println("Please enter the year of the car");
carYear = input.nextInt();
System.out.println("Please enter the current year.");
currentYear = input.nextInt();
carAge = currentYear - carYear;
System.out.println("How much does the car cost?");
costOfCar = input.nextDouble();
System.out.println("What is the sales tax rate?");
salesTaxRate = input.nextDouble();
totalCost = (costOfCar + (costOfCar * salesTaxRate));
System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f",totalCost + " " + " dollars.");

}
}

我不太确定是什么原因导致了这个问题。

最佳答案

尝试:

System.out.printf("The model of your favorite car is %s, the car is %d years old, the total of the car is %.2f dollars.", carModel, carAge, totalCost);

或者更具可读性:

System.out.printf("The model of your favorite car is %s," +
" the car is %d years old," +
" the total of the car is %.2f dollars.",
carModel, carAge, totalCost);

关于java - 在java中显示2位输出小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32857209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com