【问题标题】:Java sphere volume calculationJava球体体积计算
【发布时间】:2013-01-09 16:10:09
【问题描述】:

我有一个 Java 类,我对这个问题感到困惑。我们必须制作一个体积计算器。你输入一个球体的直径,程序会输出体积。它适用于整数,但每当我输入小数时,它就会崩溃。我假设它与变量的精度有关

double sphereDiam;
double sphereRadius;
double sphereVolume;

System.out.println("Enter the diamater of a sphere:");
sphereDiam = keyboard.nextInt();
sphereRadius = (sphereDiam / 2.0);
sphereVolume = ( 4.0 / 3.0 ) * Math.PI * Math.pow( sphereRadius, 3 );
System.out.println("The volume is: " + sphereVolume);

所以,就像我说的,如果我输入一个整数,它就可以正常工作。但是我输入了 25.4,它在我身上崩溃了。

【问题讨论】:

  • Ummm... nextInt() 不只解析整数吗?

标签: java volume calculator


【解决方案1】:

这是因为keyboard.nextInt() 期待的是int,而不是floatdouble。您可以将其更改为:

float sphereDiam;
double sphereRadius;
double sphereVolume;

System.out.println("Enter the diamater of a sphere:");
sphereDiam = keyboard.nextFloat();
sphereRadius = (sphereDiam / 2.0);
sphereVolume = ( 4.0 / 3.0 ) * Math.PI * Math.pow( sphereRadius, 3 );
System.out.println("The volume is: " + sphereVolume);

nextFloat()nextDouble() 也会拾取 int 类型,并自动将它们转换为所需的类型。

【讨论】:

  • 或者,如果您想坚持使用双打,您可以致电nextDouble() 并保留sphereDiamdouble
  • 非常感谢!有趣的是,我之前尝试过,但没有成功。我一定是打错了。再次感谢!!
【解决方案2】:
double sphereDiam;
double sphereRadius;
double sphereVolume;
System.out.println("Enter the diameter of a sphere:");
sphereDiam = keyboard.nextDouble();
sphereRadius = (sphereDiam / 2.0);
sphereVolume = ( 4.0 / 3.0 ) * Math.PI * Math.pow( sphereRadius, 3 );
System.out.println("");
System.out.println("The volume is: " + sphereVolume);

【讨论】:

  • 不要只是粘贴工作代码作为答案。解释 OP 的代码有什么问题以及他如何解决这个问题,然后(如果需要)您也可以将工作代码放入您的答案中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多