2013-10-05 32 views
-4

我無法真正弄清楚我的錯誤在下面的代碼中。另外:我的代碼看起來很不起眼,如何更好地構建它的任何建議?在Java中使用Math.pow和Math.sqrt時出錯

import java.util.*; 
import java.io.*; 
import java.lang.Math; 

public class FlightSimulator { 
public static void main(String[] args){ 

    int time; 
    int v_y; 
    int v; 
    int v_squart; 
    int height; 


    Scanner myscan = new Scanner(System.in); 
    System.out.print("Please enter the time for which you want to output the height of the " + 
      "plane "); 
    time = myscan.nextInt(); 
    if(time==0){ 
    System.out.print("The height of the plane is 456 meters over ground."); 

    } 
    else{ 
     v_y = 51 - time*3; 
     v = Math.pow(v_y+20, 2); 
     v_squart = Math.sqrt(v); 
     height = 456 - v; 
     System.out.print("The height of the plane is" + height); 

    } 
} 
} 
+3

**什麼**錯誤? –

+0

那麼......錯誤信息是什麼?至少你試圖將雙打分配給整數。 – kiheru

+0

你爲什麼要計算一個數的平方的平方根? –

回答

1
v_y = 51 - time*3; 
v = (int)Math.pow(v_y+20, 2); 
v_squart = (int)Math.sqrt(v); // why take the square root of something you just squared... 
height = 456 - v; 
System.out.print("The height of the plane is" + height); 

整數不能包含十進制值,Math.pow和Math.sqrt都返回double類型。您已聲明v_y,vv_squartint類型,您必須將操作轉換爲整數。你也可以聲明你的變量爲double類型

int time; 
double v_y; 
double v; 
double v_squart; 
double height;