gpt4 book ai didi

java - 显示最终解,显示小数点后 2 位

转载 作者:行者123 更新时间:2023-12-02 04:19:59 24 4
gpt4 key购买 nike

我正在编写一个程序,询问用户的年龄和拥有的金钱。如果他们已成年,他们将收到一条确认消息。如果不是,他们将被拒绝,并且将显示他们还剩 21 岁。钱也一样。一瓶啤酒是5美元。如果用户没有足够的钱,它会告诉他们需要多少。但是...我无法生成在响应中显示 2 位小数的值。我如何以美元金额或(例如 1.00)而不是 1.0 的形式显示解决方案或他们需要多少钱?

//import classes
import java.util.*;

public class beerLab
{
static Scanner console = new Scanner(System.in);

public static void main (String[] args)
{
// Declares the price of beer and the age required to purchase beer.
double beer = 5.00;
double moneyGiven;
int age = 21;
int ageGiven;

// Request the age from the client.
System.out.println("Please type customer age: ");
ageGiven = console.nextInt();

if (ageGiven < 21) // If the client is under 21 then their purchase will be denied.
{
System.out.println("No beer for you!" + "\n" + "Come back in " + (age - ageGiven) + " years" + "\n" + "Thank you for your patronage.");
return;
}

// Request the the amount of money the client has.
System.out.println("Type customer cash amount: ");
moneyGiven = console.nextDouble();

if (moneyGiven < beer) // If the client doesn't provide enough money, the program will tell client how much money they need.
{
System.out.println("Sorry, you need " + (beer - moneyGiven) + " more." + "\n" + "Thank you for your patronage.");
}

if (ageGiven > 21 & moneyGiven >= beer) // If the client is old enough and has enough money they can purchase the beer.
{
System.out.println("Congratulations, you can have some beer." + "\n" + "Thank you for your patronage.");
}
}
}

最佳答案

您可以使用以下语句:

System.out.format("Sorry, you need %.2f more." + "\n" + "Thank you for your patronage.\n", beer - moneyGiven);

关于java - 显示最终解,显示小数点后 2 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32895141/

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