Java:如何舍入到小数点而不保存到内存

时间:2016-09-22 20:40:46

标签: java math

嘿伙计们,我的编程课程中有一个项目可以制作二次计算器,但它的工作效果很好但是我的所有输出都需要四舍五入到小数点后5位。我可以通过使用%.5f轻松地使用已保存的变量来执行此操作,但是我的教授只希望我们将某些内容保存到变量中(如果我们多次使用它)。正如你在我的代码中看到的那样,x-intercepts等解决方案只使用了一次,因此我不允许保存它们。有没有办法强制数学字符串输出数字,如3.00000?我已经搜索过,但不知道用它搜索的技术术语很难得到答案。

public static void main(String[] args) {
    PrintStream ps = new PrintStream(System.out);
    Scanner in = new Scanner(System.in);
    ps.print("Enter the coefficient of the quadratic term -> ");
    double coefficientQuad = in.nextInt();
    ps.print("Enter the coefficient of the linear term -> ");
    double coefficientLin = in.nextInt();
    ps.print("Enter the coefficient of the constant term -> ");
    double coefficientCon = in.nextInt();
    ps.println();
    ps.printf("For the quadratic equation %.5fx^2 + %.5fx + %.5f = 0\n", coefficientQuad, coefficientLin, coefficientCon);
    ps.println();
    double discriminant = Math.pow(coefficientLin, 2) - 4 * coefficientQuad * coefficientCon;
    ps.printf("Discriminant: %.5f\n", discriminant);
    ps.println("Roots: x = {" + (-coefficientLin + Math.sqrt(discriminant)) / 2 * coefficientQuad + "," + (-coefficientLin - Math.sqrt(discriminant)) / 2 * coefficientQuad + "}");
    double axisOfSymmetry = (-coefficientLin / 2 * coefficientQuad);
    ps.printf("Axis of Symmetry: x = %.5f\n", axisOfSymmetry);
    ps.printf("Vertex: (%.5f, " + (-Math.pow(coefficientLin, 2) / 4 * coefficientQuad + coefficientCon) + ")\n", axisOfSymmetry);
    ps.println("x-intercepts: (" + (-coefficientLin + Math.sqrt(discriminant) / 2 * coefficientQuad) + ", 0.00000) and (" + (-coefficientLin - Math.sqrt(discriminant) / 2 * coefficientQuad) + ", 0.00000)");
    ps.printf("y-intercept: (0.00000, %.5f)", coefficientCon);

0 个答案:

没有答案