首頁 >電腦教學 >電腦知識 >寫一Java程式來求解一元二次方程式:ax^2 + bx + c的解

寫一Java程式來求解一元二次方程式:ax^2 + bx + c的解

WBOY
WBOY轉載
2024-01-22 11:30:191347瀏覽

用java编写一程序解一元二次方程:aX2 bX c

用java寫一程式解一元二次方程式:aX2 bX c 0

以下程序在jdk5.0測試通過

import java.util.Scanner;

public class Test {

//一元二次方程式解法

private static X fx (int a,int b,int c) throws Exception{

X x = new X();

double m = b*b - 4*a*c;

if(m>=0){

x.x1=(-1*b Math.sqrt(m))/(2*a);

x.x2=(-1*b-Math.sqrt(m))/(2*a);

return x;

}

else throw new Exception("無解");

}

public static void main(String[] args) {

try{

//輸入參數a,b,c

#Scanner cin=new Scanner(System.in);

System.out.print("a=");

int a = cin.nextInt();

System.out.print("b=");

int b = cin.nextInt();

System.out.print("c=");

int c = cin.nextInt();

//計算

X x=fx(a,b,c);

//顯示

System.out.println("\n1x1=" x.x1 "\nx2=" x.x2);

}catch(Exception e){

#System.out.println(e.getMessage());

}

}

}

//一元二次方程式解集包裝類別

class X{

double x1;

double x2;

}

用Java來解一元二次方程式:aX2 bX c 0

public static main(String[] arg0){

if(arg0== null || arg0.length == 0){

System.out.println("請輸入參數:a,b,c");

System.exit(0);

}

for(int i=0;i

try {

Float.parseFloat(arg0[i]);

} Catch(Exception e){

#System.out.println("請輸入數字");

System.exit(0);

}

}

float a = Float.parseFloat(arg0[0]);

float b = 0;

float c = 0;

if(arg0.length >= 2){

b = Float.parseFloat(arg0[1]);

}

if(arg0.length >= 3){

c = Float.parseFloat(arg0[2]);

}

float tmp = b*b - 4*a*c;

if(tmp

System.out.println("x無實數根");

System.exit(0);

}

if(a==0 & b==0 & c==0){

System.out.println("x有任意實數根");

System.exit(0);

}

float result = (-1)*b/(2*a);

if(tmp == 0){

System.out.println("x1=x2=" result);

System.exit(0);

}

float x1 = ((-1)*b java.lang.Math.sqrt(tmp))/(2*a);

float x2 = ((-1)*b-java.lang.Math.sqrt(tmp))/(2*a);

System.out.println("x1=" x1);

System.out.println("x2=" x2);

}

java程式一元三次方程式a x x x b x x c x d 0的根

import java.io.*;

public class Test1

{

public static void main(String[] args) throws IOException

{

double a,b,c,d,x,y;

System.out.println("一元三次方程式解:y=ax3 bx2 cx d");

System.out.println("請輸入a值:");

BufferedReader in1=new BufferedReader(new InputStreamReader(System.in));

a=Double.parseDouble(in1.readLine());

System.out.println("請輸入b值:");

BufferedReader in2=new BufferedReader(new InputStreamReader(System.in));

b=Double.parseDouble(in2.readLine());

System.out.println("請輸入c值:");

BufferedReader in3=new BufferedReader(new InputStreamReader(System.in));

c=Double.parseDouble(in3.readLine());

System.out.println("請輸入d值:");

BufferedReader in4=new BufferedReader(new InputStreamReader(System.in));

d=Double.parseDouble(in4.readLine());

System.out.println("請輸入x值:");

BufferedReader in5=new BufferedReader(new InputStreamReader(System.in));

x=Double.parseDouble(in5.readLine());

y=a*Math.pow(x, 3) b*Math.pow(b,2) c*x d;

System.out.println("y值為:" y);

}

}

以上是寫一Java程式來求解一元二次方程式:ax^2 + bx + c的解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:docexcel.net。如有侵權,請聯絡admin@php.cn刪除