Cur*_*115 4 java volume calculator
我有一个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);
Run Code Online (Sandbox Code Playgroud)
所以,就像我说如果我输入一个整数,它工作正常.但是我输了25.4并且它在我身上崩溃了.
这是因为keyboard.nextInt()期待一个int,而不是一个float或double.您可以将其更改为:
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);
Run Code Online (Sandbox Code Playgroud)
nextFloat()和nextDouble()将拾取器int的类型,以及,并自动将其转换为所需的类型.
| 归档时间: |
|
| 查看次数: |
27134 次 |
| 最近记录: |