使用JAVA Loop进行数学计算

时间:2017-01-14 21:04:57

标签: java

我曾试图做一些计算,而且还有一些东西并没有相加。我试图实现下面的截图 expected

但这就是我得到的

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 个答案:

答案 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类。