gpt4 book ai didi

java - Java中添加小数位(小数点后3位)

转载 作者:行者123 更新时间:2023-12-01 23:01:53 25 4
gpt4 key购买 nike

我想知道如何使以下程序中的 avg 四舍五入到小数点后 3 位:

public class BaseballCalculator {
public static void main(String args[]) {
Scanner myScanner = new Scanner(System.in);
double atBats;
double baseHits;
double onBase;
double avg;
double onBasePercentage;

System.out.println("How many atbats did you have? ");
atBats = myScanner.nextDouble();

System.out.println("How many base hits and homeruns did you have? ");
baseHits = myScanner.nextDouble();

System.out.println("How many times did you get a hit by pitch or walk? ");
onBase = myScanner.nextDouble();

avg = baseHits / atBats;
onBasePercentage = (baseHits + onBase) / atBats;

System.out.println("You have a total of " + baseHits + " base hits for the season");
System.out.println("You have a total of " + atBats + " at bats for the season");
System.out.println("Your average for the game or season is: " + avg);
System.out.println("Your on base percentage for the game or year is: " + onBasePercentage);
}
}

最佳答案

使用String.format将输出格式化为小数点后 3 位。输出被舍入。

System.out.println("Your average for the game or season is: " +
String.format("%.3f", avg));

关于java - Java中添加小数位(小数点后3位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23302785/

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