面向对象的第二次pta作业第一题:求一元二次方程
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); double eqn[] = new double[3]; eqn[0] = input.nextDouble(); eqn[1] = input.nextDouble(); eqn[2] = input.nextDouble(); double roots[] = new double[2]; if(eqn[0]==0) { System.out.println("Wrong Format"); System.exit(0); } int n = solveQuadratic(eqn, roots); if(n == 2) System.out.printf("The equation has two roots: %.4f and %.4f", roots[0],roots[1]); else if(n == 1) System.out.printf("The equation has one root: %.4f",roots[0]); else System.out.println("The equation has no roots"); } public static int solveQuadratic(double[] eqn, double[] roots) { int s = 0; double a=eqn[0],b=eqn[1],c=eqn[2]; double d = b*b-4*a*c; if(d>0) { s=2; roots[0] = ((-1)*b+Math.sqrt(d))/2/a; roots[1] = ((-1)*b-Math.sqrt(d))/2/a; } else if(d==0) { s=1; if (b==0&&c==0) { roots[0] = 0.0000; } else roots[0] = (-1)*b/2/a; } return s; } }
这次作业是把上一次的第一题用方法来写啦~
和c语言里面的函数差不多耶