2017-02-04 178 views
0

我試圖讓它每次打印結果列表的時間是一個整數(ei,2.0,4.0,12.0等),但它只打印第一行結果。 if條件是否錯誤?或我的命令打印值?問題結果打印表

package a03;

import java.util.Scanner;

/** * * @author卡爾文(A00391077)該程序模擬了一個大炮在預置 *由用戶設置的擊發。 */ 公共類大炮{

public static final double DELTA_T = 0.001; 
public static final double GRAVITY = 9.81; 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 

    //variables 
    Scanner kbd = new Scanner(System.in); 
    double muzzleVelocity, muzzleHeight, time, height, velocity; 

    //introducing program 
    System.out.println("Cannon Simulation"); 
    System.out.println("-----------------"); 
    System.out.println(); 
    System.out.println("This program simulates firing a cannon straight" 
      + "up into the air. Velocity"); 
    System.out.println("is measured in metres per second squared and" 
      + " height in meteres."); 
    System.out.println(); 
    System.out.println("By Calvin Elliott (A00391077"); 
    System.out.println(); 
    System.out.println("...press enter..."); 
    kbd.nextLine(); 
    System.out.println(); 

    //getting muzzle velocity 
    System.out.println("What is the muzzle velocity of the projectile?"); 
    muzzleVelocity = kbd.nextDouble(); 

    while (muzzleVelocity <= 0) { 
     System.out.println("The velocity must be positive"); 
     System.out.println("What is the muzzle velocity of the projectile?"); 
     muzzleVelocity = kbd.nextDouble(); 
    } 

    //getting muzzle height 
    System.out.println("what height is the muzzle above the ground?"); 
    muzzleHeight = kbd.nextDouble(); 

    while (muzzleHeight <= 0) { 
     System.out.println("The position must be positive"); 
     System.out.println("What height is the muzzle above the ground?"); 
     muzzleHeight = kbd.nextDouble(); 

    } 

    //calculations 
    height = muzzleHeight; 
    velocity = muzzleVelocity; 
    time = 0; 

    System.out.println("TIME HEIGHT VELOCITY"); 
    System.out.println("---- ------ --------"); 

    while (height > 0) { 
     if ((time % 1.0) < DELTA_T) { 
      System.out.printf("%6.2f%10.3f%10.3f\n", time, height, velocity); 

     } 
     height = (height + (velocity * time)); 
     velocity = (velocity - (GRAVITY * time)); 
     time = (time + 0.001); 

    } 

} 

}

+0

你有沒有試過時間%1.0 == 0? – MacStation

回答

1

您通過velocity * time,這是時間的絕對量每次迭代增加高度。你需要的時候,而不是增加它增加DELTA_T

例如:

while (height > 0) { 
    if ((time % 1.0) < DELTA_T) { 
     System.out.printf("%6.2f%10.3f%10.3f\n", time, height, velocity); 

    } 
    height = (height + (velocity * DELTA_T)); 
    velocity = (velocity - (GRAVITY * DELTA_T)); 
    time = (time + DELTA_T); 

} 

另外值得一提的比重一般應爲負值,這樣就可以把它添加到速度,你一樣將速度添加到位置。

+0

現在這一切都很有意義。非常感謝。 –

+0

@CalElliott,你是新來的。一個好的做法是接受最好的答案。左邊的複選標記... –