在Java中使用Math.pow和Math.sqrt时出错

时间:2013-10-05 20:51:39

标签: java math

我无法确定下面代码中的错误。另外:我的代码看起来如此不雅,任何建议如何更好地构建它?

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

    }
}
}

1 个答案:

答案 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_yvv_squart声明为int类型,您必须将操作转换为整数。您还可以将变量声明为double个类型

int time;
double v_y;
double v;
double v_squart;
double height;
相关问题