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)。

如果您将行更改为这样(将每个整数替换为双精度):

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

那么结果就会不一样。

于 2013-02-18T18:10:09.650 回答