0

//次のコード行では、ユーザーは正二十面体の体積を決定するために長さを入力するように求められますが、入力すると、プログラムは常に体積の答えとして0.0を出力します???

import java.io.*; //allows I/o statements

class VolumeIcosahedron //creating the 'volumeIcosahedron' class
{
  //allows strings with exceptions to IO = input/output
  public static void main (String[] args) throws IOException
  {
    BufferedReader myInput = new BufferedReader(
                   new InputStreamReader (System.in)); //system input/ output

    String stringNum; // the number string
    double V; // integer with decimals volume
    int L; // integer required length

    //System output
    System.out.println("Hello, what is the required length");
    stringNum  = myInput.readLine();

    L = Integer.parseInt(stringNum);
    V =  5/12 *(3 + Math.sqrt(5))*(L*L*L);                      

    System.out.println("The volume of the regular Icosahedron is " + V);  
  }
}
4

3 に答える 3

1

5/12整数は等しいので0、常に結果になり0ます。

5.0整数除算を伴わずに除算を強制するようにしてください。

V = 5.0/12 *(3.0 + Math.sqrt(5))*(L*L*L);  
于 2013-02-18T17:59:27.320 に答える
1

私はこれが問題のある行だと思います:

V          =  5/12 *(3 + Math.sqrt(5))*(L*L*L);

5/12はint(整数)を返します。これは常に0に切り捨てられるため、0*すべてが0を返します。

文字dを使用して、これらの数値がdouble型であることを示すために、これに変更します。

V          =  5d/12d *(3 + Math.sqrt(5))*(L*L*L); 
于 2013-02-18T18:00:10.717 に答える
1

その理由は、計算内で整数を使用しているためです。整数の場合、除算はユークリッド演算、つまりa = bq+rと見なす必要があります。したがって、プログラムでは、5/12は常に0(5 = 0 * 12 + 5)を返します。

行を次のように変更した場合(すべての整数をdoubleに置き換えます):

V = 5.D/12.D *(3.D + Math.sqrt(5.D))*(L*L*L);

その場合、結果は異なります。

于 2013-02-18T18:10:09.650 に答える