2017-01-14 42 views
-2

我曾嘗試做一些計算,但有些東西不太合理。我想實現以下 expected使用JAVA循環進行數學計算

的截圖,但是這是我得到

result

請我需要一些幫助,這是我迄今所做

public class VelocityFall 
{ 
public static void main (String [] a) 
{ 
    Scanner s = new Scanner (System.in); 
    System.out.print("This program prints a table that shows each \nsecond,"  
    + 
    "height from the ground (meters), and the velocity (m/s)\n of a free-falling" + 
    "object from an initial height (metres).\nPlease input the Initial Height H: "); 


    // input/get the value of H from the keyboard 
    double H = s.nextDouble(); 
    // we need to design/output the table by using println with lines and tabs (\t) 

    System.out.println ("------------------------------------------"); 
    System.out.println (" t(s)\t\tHeight(m)\t\tVelocity(m/s)"); 
    System.out.println ("------------------------------------------"); 

    //we now require a for loop 
    for (int t = 0; t<=15; t++) 
    { 
    // we are now going to calculate and output the velocity and decreasing 
    height 
    double velocity = 9.8*t; 
    H = H-(0.5*9.8*Math.pow(t,2)); 
    System.out.println(t + "\t\t" + H + "\t\t" + velocity); 

    } 
    } 
} 
+1

我從運動學開始已經很長時間了,但是不應該從初始高度計算H,而不是從前一個高度計算H? –

+0

您可以編輯您的問題,以便更好地格式化,並且可以請您解釋*您正在嘗試做什麼*。 「有些計算」並不是什麼東西,那只是一個寬鬆的話,你想要做什麼確切的計算,哪些輸入,輸出如何不同,以及相當重要:你在代碼中隔離了什麼問題,你有什麼試圖解決它,但最終沒有得到它的工作? –

回答

2

您的問題是,您正在重新分配下面一行中的H變量。

H = H-(0.5*9.8*Math.pow(t,2)); 

將該行替換爲下面的行以獲得正確的輸出。

double H_new = H-(0.5*9.8*Math.pow(t,2)); 

不要忘記改變變量在println電話太:

System.out.println(t + "\t\t" + H_new + "\t\t" + velocity); 

這樣,H變量保持等於用戶的輸入和你的計算不受影響通過前面的計算結果。


輸出:

t(s)  Height(m)  Velocity(m/s) 
------------------------------------------ 
0  1234.56  0.0 
1  1229.6599999999999  9.8 
2  1214.96  19.6 
3  1190.46  29.400000000000002 
4  1156.1599999999999  39.2 
5  1112.06  49.0 
6  1058.1599999999999  58.800000000000004 
7  994.4599999999999  68.60000000000001 
8  920.9599999999999  78.4 
9  837.6599999999999  88.2 
10  744.56  98.0 
11  641.6599999999999  107.80000000000001 
12  528.9599999999999  117.60000000000001 
13  406.4599999999999  127.4 
14  274.15999999999985  137.20000000000002 
15  132.05999999999995  147.0 

至於重複數字的問題,請嘗試使用DecimalFormat類。