從這個程序中學到的:
1 throws IOExceptiom 在這里不如用try catch方便
2 已經(jīng)創(chuàng)建類的方法的調(diào)用
//計算一個一元二次方程
import java.io.*;
class InputData //建造一個從鍵盤獲取數(shù)據(jù)的累
{
?private static String s="";
?public static void input()
?{
??BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
??try
??{
???s=in.readLine();
??}catch (IOException e){}
??
?}
?static public float getFloat()
?{
??
??input();//調(diào)用input方法
??return Float.parseFloat(s);
? }
}
class Equation? //建造一個表示方程式的類
{
?float a,b,c,disc=0;
?void input()? //三個參數(shù)輸入的方法
?{
??System.out.println("請輸入3個參數(shù) a,b,c:");
??System.out.println("a=");
??a=InputData.getFloat();//調(diào)用自定義的InputData類中的input方法
??System.out.println("b=");
??b=InputData.getFloat();
??System.out.println("c=");
??c=InputData.getFloat();
?}
?void getRoots() //獲得根的方法
?{?? double x1, x2;
???? double realpart,imagpart;
??if (Math.abs(a)<1e-5)//判斷是否為一元二次方程
??{
???System.out.println("這不是一個一元二次方程");
????? System.exit(0);//退出程序
??}
??else
??{
???System.out.println("這是一個一元二次方程");
???disc=b*b-4*a*c;
?????
???if(disc<=1e-5)
???{
????x1=(-b)/(2*a);
????x2=(-b)/(2*a);
????System.out.println("此一元二次方程有兩個相等的根:x1=x2="+x1);
???}
???else if(disc>1e-5)
???{
????x1=(-b+Math.sqrt(disc))/(2*a);
????x2=(-b-Math.sqrt(disc))/(2*a);
????System.out.println("這個一元二次方程有兩個實根:"+"\nx1="+x1+"\nx2"+x2);
???}
???else
???{
????realpart=(-b)/2*a;
????imagpart=Math.sqrt(-disc);
????System.out.println("這個一元二次方程有兩個復(fù)數(shù)根:");
????System.out.println("x1="+realpart+"+"+imagpart+"i");
????System.out.println("x2="+realpart+"-"+imagpart+"i");
???}
??}
??
? }?
}
?
/**
?* @author Administrator
?*
?*/
public class roots //主類
{
?public static void main (String[] args)
?{
??Equation e=new Equation();
??e.input();
??e.getRoots();
??
?}
}
?
?
?
?
?
?
?
?
?
?
posted @ 2006-07-19 14:48 firslien 閱讀(349) | 評論 (0) | 編輯 收藏