面向对象的第三次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 a = Double.parseDouble(input.next()); double b = Double.parseDouble(input.next()); double c = Double.parseDouble(input.next()); if(a == 0){ System.out.println("Wrong Format"); System.exit(0); } //create a QuadraticEquation object QuadraticEquation equation = new QuadraticEquation(a, b, c); //get value of b * b - 4 * a * c double discriminant = equation.getDiscriminant(); System.out.println("a=" + equation.getA() + ",b=" + equation.getB() + ",c=" + equation.getC()+":"); if (discriminant < 0) { System.out.println("The equation has no roots."); } else if (discriminant == 0) { System.out.println("The root is " + String.format("%.2f", equation.getRoot1())); } else // (discriminant >= 0) { System.out.println("The roots are " + String.format("%.2f", equation.getRoot1()) + " and " + String.format("%.2f", equation.getRoot2())); } } } class QuadraticEquation{ private double a; private double b; private double c; public QuadraticEquation() { } public QuadraticEquation(double a,double b,double c) { this.a = a; this.b = b; this.c = c; } public double getA() { return a; } public double getB() { return b; } public double getC() { return c; } public double getDiscriminant() { double d = b*b-4*a*c; return d; } public double getRoot1() { return ((-1)*b+Math.sqrt(getDiscriminant()))/2/a; } public double getRoot2() { return ((-1)*b-Math.sqrt(getDiscriminant()))/2/a; } }
啊!学新东西了!!!!!
终于和c不一样了!!!!!!!!
一元二次方程的3.0版本噢~
从单纯地用主函数到加入方法,再到类的运用
虽然这道题不是很难
我没有很大体会到类的意义
但是我会好好学的!!!!!!!!!!!
太感人了