我正在写一个非常简单的程序,其中用户试图找出他是否改变煎饼的直径(新旧直径都是用户输入的),给定数量(用户输入),多少煎饼与他可以制作新的直径。现在我的计算与测试数据一起工作:10个旧直径,8个旧数量,4个新直径。这导致50个新煎饼是正确的,但是当我输入5个旧直径,10个旧数量,10个新直径。这导致1.59999新的煎饼不正确,答案应该是2.5。这是我的代码,任何帮助将不胜感激:
import java.util.Scanner;
public class pancakes {
public static void main(String[] args) {
int diameterOld = 0; // used to save diameter of original pancakes
int quantityOld = 0; // used to save quantity of original pancakes
int diameterNew = 0; // used to save diameter of new pancakes
double quantityNew = 0; // used to save quantity of new pancakes
double areaNew = 0; // used to store area of new pancakes
double areaOld = 0; // used to store area of original pancakes
double totalSurfaceArea = 0; // total amount of batter used
Scanner input = new Scanner(System.in); // allows keyboard input
System.out.println ("Mohammad's java Pancakes");
System.out.print ("Diameter of original pancakes (inches): "); // Prints statement asking for diameter of original pancakes
diameterOld = input.nextInt(); // saves input into diameterOld
System.out.print ("Quantity of original pancakes: "); // Prints statement asking for quantity of original pancakes
quantityOld = input.nextInt(); // saves input into quantityOld
System.out.print ("Diameter of new pancakes (inches): "); // Prints statement asking for diameter of new pancakes
diameterNew = input.nextInt(); // saves input into diameterNew
areaOld = ((diameterOld/2)*(diameterOld/2)*Math.PI); // calculates area of original pancakes
totalSurfaceArea = (areaOld * quantityOld); // calculates total amount of batter needed
areaNew = ((diameterNew/2)*(diameterNew/2)*Math.PI); // calculates area of new pancakes
quantityNew = (totalSurfaceArea/areaNew); // calculates quantity of new pancakes
System.out.println ("Quantity of new pancakes: " + quantityNew); // Prints statement stating quantity of new pancakes and amount of new pancakes
input.close(); // Closes scanner input
}
}
答案 0 :(得分:1)
当你将(diameterOld/2)
和同样的表达式分开时,你要划分两个整数,因此结果将是一个整数。因此,如果diameterOld
等于5,则(diameterOld/2)
不会按预期给出2.5
,而是截断为整数,因此您获得2
。
要更正此问题,请在执行除法之前将其中一个整数值转换为double,例如:(diameterOld/2.0)
答案 1 :(得分:1)
您正在使用diameterOld
(两次)和diameterNew
(两次)执行4次整数除法,这在Java中会产生另一个整数。即使数学结果为2.5
,Java也会将其截断为2
(int
)。
更改除以double
文字以从头开始强制浮点数学,例如:
diameterOld/2.0
同样适用于其他部门。
此外,您将totalSurfaceArea
除以areaNew
,两者都将直径除以2
并乘以pi。在数学上,那些在分区中取消,所以你甚至不需要打扰除2
或乘以pi。
areaOld = diameterOld * diameterOld;
和
areaNew = diameterNew * diameterNew;
这在计算quantityNew
时会以数学方式保留。
输出:
Mohammad's java Pancakes
Diameter of original pancakes (inches): 5
Quantity of original pancakes: 10
Diameter of new pancakes (inches): 10
Quantity of new pancakes: 2.5
答案 2 :(得分:0)
你旧区域的代码应该是
areaOld = (((double)(diameterOld/2))*((double)(diameterOld/2))*Math.PI);
areaNew = (((double)(diameterNew/2))*((double)(diameterNew/2))*Math.PI);