gpt4 book ai didi

java - 尽管我应该收到数值,但我收到输出 0.0

转载 作者:行者123 更新时间:2023-12-02 12:13:44 25 4
gpt4 key购买 nike

请帮忙。我试图找到击球率和上垒率。无论我输入多少数字,我的输出最终都是 0.0,但是当我使用计算器时,我最终会得到不同的结果。另外,在我的说明中,我被告知将数字作为整数值输入,并将输出四舍五入到最接近的千分位。

import java.io.*;
import java.util.*;
public class Prog52d
{
public static void main (String args[])
{
Scanner kbReader=new Scanner(System.in);
//input
System.out.println("Enter Player's Name");
String name=kbReader.next();
System.out.println("Enter Number of Times at bat.");
int timesAtbat=kbReader.nextInt();
System.out.println("Enter Number of Hits.");
int hits=kbReader.nextInt();
System.out.println ("Enter Number of Walks.");
int walks=kbReader.nextInt();
//calculates the batting average
double battingAverage=hits/timesAtbat;
battingAverage= Math.round(battingAverage*1000.0)/1000.0;
//calculates the on base percentage
double onBasepercentage= (hits+walks)/(timesAtbat);
onBasepercentage= Math.round(onBasepercentage*1000.0)/1000.0;

System.out.println("Player "+name+ " has a ");
System.out.println("batting average of " + battingAverage + " and");
System.out.println(" an On Base Percentage of " + onBasepercentage);
}
}

最佳答案

您使用代码

 double battingAverage = hits / timesAtbat;

其中 hitstimesAtBat 是整数。这会调用基于 int 的除法,它只会返回 int 值。然后 int 值将被转换为 double。

由于击球次数不可能超过击球次数,因此大多数人都会遇到这样的情况

double battingAverage = hits / timesAtbat;
double battingAverage = 30 / 150;
double battingAverage = 0;
double battingAverage = 0.0;

您需要将 hitstimesAtBat 转换为 double 以获得基于 double 的除法。

double battingAverage = ((double)hits) / ((double)timesAtbat);
double battingAverage = ((double)30) / ((double)150);
double battingAverage = 30.0 / 150.0;
double battingAverage = 0.2;

您的其他问题类似。

关于java - 尽管我应该收到数值,但我收到输出 0.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46349180/

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