好的继承人我的任务问题
创建一个名为DrivingCost的Java程序,提示用户输入驾驶距离,汽车的燃油效率(英里/加仑)和每加仑的价格,然后显示行程的成本:
我应该得到$ 81.40的结果,但我一直得到$ 81.39 我如何围绕那一分钱?
这是我的代码
import java.util.Scanner;
public class DrivingCost
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the driving distance: ");
double distance = input.nextDouble();
System.out.print("Enter miles per gallon: ");
double mpg = input.nextDouble();
System.out.print("Enter price per gallon: ");
double ppg = input.nextDouble();
double cost = distance / mpg * ppg;
System.out.println("The cost of driving is $" + (int)(cost * 100) / 100.0);
}
}
答案 0 :(得分:0)
...试
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
public class DrivingCost
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the driving distance: ");
double distance = input.nextDouble();
System.out.print("Enter miles per gallon: ");
double mpg = input.nextDouble();
System.out.print("Enter price per gallon: ");
double ppg = input.nextDouble();
double cost = (distance / mpg) * ppg;
input.close();
NumberFormat df = DecimalFormat.getCurrencyInstance(Locale.US);
System.out.println("The cost of driving is " + df.format(cost));
}
}