- package cn.edu.xaut.junit;
- import cn.edu.xaut.exception.*;
- public class Equation {
- private static float x1;
- private static float x2;
- private static float x;
- private static float real;
- private static float imag;
- private static float[] results;
-
- private static float a;
- private static float b;
- private static float c;
-
- private static float delt;
- public static float[] calc(float w,float p,float q)throws Exception{
- results=new float[2];
- a=w; b=p; c=q;
- if(0.0f==a){ //bx+c=0; x=-c/b;
- if(0.0f!=b){
- x=-c/b;
- results[0]=x;
- print();
- return results;
- }
- else{
- throw new MyArithmeticException("除数不能为0");
- }
-
- }else{
- delt=b*b-4*a*c;
- if(delt>=0){
- x1=(float) ((-b+Math.sqrt(delt))/(2*a));
- x2=(float) ((-b-Math.sqrt(delt))/(2*a));
- results[0]=x1;
- results[1]=x2;
- print();
- return results;
-
- }else{
- real=-b/(2*a);
- imag=(float) (Math.sqrt(-delt)/(2*a));
- results[0]=real;
- results[1]=imag;
- print();
- return results;
- }
- }
- }
-
- public static void print(){
- if(0.0f==a){
- if(0.0f!=b){
- System.out.println("该方程是一元一次方程,其根为:x="+results[0]);
- }else{
- System.err.println("不是一个方程!");
- }
- }else{
- if(delt>=0){
- System.out.println("该方程是一元二次方程,两根分别为:x1="+results[0]+",x2="+results[1]);
- }else{
- System.out.println("该一元二次方程的根为复数,两根分别为:x1="+results[0]+"+"+results[1]+"i"+",x2="+results[0]+"-"+results[1]+"i");
- }
- }
- }
- }
- package cn.edu.xaut.exception;
- public class MyArithmeticException extends Exception {
- public MyArithmeticException() {
- }
- public MyArithmeticException(String message) {
- super(message);
- }
- public MyArithmeticException(Throwable cause) {
- super(cause);
- }
- public MyArithmeticException(String message, Throwable cause) {
- super(message, cause);
- }
- }
- package test;
- import org.junit.Assert;
- import org.junit.Test;
- import cn.edu.xaut.junit.Equation;
- public class EquationTest {
- @Test
- public void testCalc() {
- float a = 1.0f;
- float b = 2.0f;
- float c = 1.0f;
- float[] expecteds = {-1.0f,-1.0f };
- //float[] expecteds = {-0.5f,0.5f};
- //float expecteds =-0.5f;
- float[] results;
- try {
- results = Equation.calc(a, b, c);
- Assert.assertArrayEquals(expecteds, results, 0.0f);
- //Assert.assertEquals(expecteds,results[0],0.0f);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
优秀的代码是调试出来的,这个代码设计是参考Math.sqrt()
欢迎大家拍砖!
附上源码:
阅读(2900) | 评论(0) | 转发(0) |