即使我应该收到数字值,我收到输出0.0

时间:2017-09-21 16:46:21

标签: java

请帮忙。我试图找到击球率和击球率。无论我输入的数字,我的输出最终都是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);
}
}

3 个答案:

答案 0 :(得分:1)

您使用代码

 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 battingAverage = ((double)hits) / ((double)timesAtbat);
double battingAverage = ((double)30) / ((double)150);
double battingAverage = 30.0 / 150.0;
double battingAverage = 0.2;

您的其他问题类似。

答案 1 :(得分:0)

Int / int = int(以类型表示),因此您必须将您的输入值读取为double或在之后但在计算之前将其转换。

答案 2 :(得分:0)

 double battingAverage=hits/timesAtbat;

这会给你一个整数结果,因为hitstimeAtbat都是整数。

将至少其中一个投射到double,以便将结果的数据类型提升一倍:

 double battingAverage = (double)hits / timesAtbat;

 double battingAverage = hits / (double)timesAtbat;