int single = 0, doub=0, triple=0, homer=0, atbats=0, totalbase, totalhits;
double slug, battingavg;
Scanner sc = new Scanner(System.in);
System.out.print("Enter singles (-1 to end): ");
single = sc.nextInt();
while (single != -1)
{
System.out.print("Enter doubles: ");
doub = sc.nextInt();
System.out.print("Enter triples: ");
triple = sc.nextInt();
System.out.print("Enter home runs: ");
homer = sc.nextInt();
System.out.print("Enter total at bats: ");
atbats = sc.nextInt();
System.out.print("Enter the player's name: ");
String name = sc.next();
totalbase = (single + doub * 2 + triple * 3 + homer * 4);
slug = totalbase / atbats;
battingavg = (single + doub + triple + homer) / atbats;
System.out.println("Player's name is " + name);
System.out.printf("The slugging percentage is %.3f\n", + slug);
System.out.printf("The batting percentage is %.3f\n", + battingavg);
System.out.print("Enter singles (-1 to end): ");
single = sc.nextInt();
}
该程序在计算后只输出1或0。其他一切都很好,但它似乎没有做计算。
答案 0 :(得分:3)
问题是当你进行整数除法时,你会得到整数值。而是使用double
或float
数据类型。我看到slug
和battingavg
已经double
,但您要为它们分配整数除法的结果。如果将计算中的至少一个值转换为double
,则应获得预期的输出。例如:
slug = totalbase / (double) atbats;
battingavg = (single + doub + triple + homer) / (double) atbats;
答案 1 :(得分:1)
当你对整数值进行除法并将结果存储在一个加宽转换的double
时,但该值被计算为一个整数,因此你可以扩大整数值。
改变这一点,
slug = totalbase / atbats;
battingavg = (single + doub + triple + homer) / atbats;
这样的事情,
slug = ((double) totalbase / atbats);
battingavg = ((double) (single + doub + triple + homer) / atbats);
将double
值转换为double
变量。