This question already has answers here:
Simple division in Java - is this a bug or a feature?
(5个答案)
在8个月前关闭。
我的目标是获取球体的宽度,将其转换为半径,找到以英寸为单位的面积,然后以英尺为单位。
然后以英寸为单位,然后以英尺为单位计算体积。
该区域工作正常,但是在计算体积时会以奇怪的形式出现,而不是正确的数字
我的公式和变量看起来不错,所以我真的不知道下一步该怎么做
这是用户输入宽度为400后读取的输出
输入球体的宽度:
400
整数除法= 200.0(正确)
球体的面积是:502400.0(正确)
英尺球的面积是3488.8888888888887(正确)
以英寸为单位的球体体积为2.512E7(不正确)
以英尺为单位的球体的体积为14537.037037037036(不正确)
加仑1943.454149336502
我希望以英寸为单位的球体输出约为33,493,333
脚的范围约为19,383
(5个答案)
在8个月前关闭。
我的目标是获取球体的宽度,将其转换为半径,找到以英寸为单位的面积,然后以英尺为单位。
然后以英寸为单位,然后以英尺为单位计算体积。
该区域工作正常,但是在计算体积时会以奇怪的形式出现,而不是正确的数字
我的公式和变量看起来不错,所以我真的不知道下一步该怎么做
System.out.println("Enter the width of the sphere: ");
Scanner sc = new Scanner(System.in); // enables scanner
p = sc.nextInt(); //scans user input for width
q = 2; // var used to divide width by 2
r = p/q; // user input divded by 2 to get radius
System.out.println("Division of the integers = "+r);
double pi = 3.14;
double r2 = r * r; // radius squared
double r3 = r*r*r; // radius cubed
double a2 = 4 * pi * r2; // area formula
double volume = 4/3 * pi * r3; // volume formula for
double v2g = 7.48; // gallons convert
System.out.println("the area of the sphere is:" + a2 );
System.out.println("the are of the sphere in feet is"+ a2 / 144);
System.out.println("the volume of the sphere in inches is" + volume);
System.out.println("the volume of the sphere in feet is" + volume / 1728);
这是用户输入宽度为400后读取的输出
输入球体的宽度:
400
整数除法= 200.0(正确)
球体的面积是:502400.0(正确)
英尺球的面积是3488.8888888888887(正确)
以英寸为单位的球体体积为2.512E7(不正确)
以英尺为单位的球体的体积为14537.037037037036(不正确)
加仑1943.454149336502
我希望以英寸为单位的球体输出约为33,493,333
脚的范围约为19,383
最佳答案
4/3
等于1
,因为它是整数除法。您应该改用4.0 / 3
(或任何其他执行浮点除法的方法)。
顺便说一句,您要使用Math.PI
:https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#PI