一元二次方程求根JAVA源程序代码
方程求根程序

#include<iostream>#include<cmath>#include<iomanip>using namespace std;#define PI 3.141592653double x0,x1,x2,x[20];double e[20];double f(double x){return cos(x)-0.5;}void print1(int n){int j;cout<<"Iteration Error e[n+1]/e[n]"<<endl;for(j=0;j<n;j++)if(j<n-1)cout<<setw(8)<<j<<" "<<setw(20)<<x[j]-PI/3<<" "<<setw(20)<<e[j+1]/e[j]<<endl;else cout<<setw(8)<<j<<" "<<setw(20)<<x[j]-PI/3<<" "<<endl<<endl;}void print2(int n){int j;cout<<"Iteration Error e[n+1]/e[n] e[n+1]/e[n]^2"<<endl;for(j=0;j<n;j++)if(j<n-1)cout<<setw(8)<<j<<" "<<setw(20)<<x[j]-PI/3<<" "<<setw(20)<<e[j+1]/e[j]<<" "<<setw(20)<<e[j+1]/pow(e[j],2)<<endl;else cout<<setw(8)<<j<<" "<<setw(20)<<x[j]-PI/3<<" "<<endl<<endl;}void print3(int n){int j;cout<<"Iteration Error e[n+1]/e[n] |e[n+1]|/|e[n]|^1.618"<<endl;for(j=0;j<n;j++)if(j<n-1)cout<<setw(8)<<j<<" "<<setw(20)<<x[j]-PI/3<<" "<<setw(20)<<e[j+1]/e[j]<<""<<setw(20)<<fabs(e[j+1])/pow(fabs(e[j]),1.618)<<endl;else cout<<setw(8)<<j<<" "<<setw(20)<<x[j]-PI/3<<" "<<endl<<endl;}void Bisection(){cout<<"******************result of Bisection**********************"<<endl;cout<<"初始化x1=0,x2=PI/2"<<endl;x1=0;x2=PI/2;int i=0;while(1){x[i]=(x1+x2)/2;e[i]=x[i]-PI/3;if(f(x1)*f(x[i])>0)x1=x[i];else if(f(x2)*f(x[i])>0)x2=x[i];elsex1=x2=x[i];i++;if(16==i)break;}print1(i);}void linearinterpolation(){cout<<"*****************result of linearinterpolation******************"<<endl;cout<<"初始化x1=0,x2=PI/2"<<endl;x1=0;x2=PI/2;int i=0,j;while(1){x[i]=(x1*f(x2)-x2*f(x1))/(f(x2)-f(x1));e[i]=x[i]-PI/3;if(f(x1)*f(x[i])>0)x1=x[i];else if(f(x2)*f(x[i])>0)x2=x[i];elsex1=x2=x[i];i++;if(16==i)break;}}void linearinterpolation(){int i=0;cout<<"**********************************result of Nowton Raphson*********************************"<<endl;cout<<"初始化x0=PI/2"<<endl;x0=PI/2;while(1){x0=x0-(f(x0)/(-sin(x0)));x[i]=x0;e[i]=x0-PI/3;i++;if(5==i)break;}print2(i);}void Secant(){cout<<"***********************result of Secant**********************"<<endl;cout<<"初始化x0=0,x1=PI/2"<<endl;x0=0;x1=PI/2;int i=0;while(1){if(0==i%2){x0=x1-(x1-x0)*f(x1)/(f(x1)-f(x0));x[i]=x0;}else{x1=x0-(x0-x1)*f(x0)/(f(x0)-f(x1));x[i]=x1;}e[i]=x[i]-PI/3;i++;if(i==7)break;}}double g(double x){return x+cos(x)-0.5;}void Directiteration1(){cout<<"*********************result of Direct iteration1****************"<<endl;cout<<"初始化x0=0"<<endl;x0=0;int i=0;x0=g(x0);e[i]=x0-PI/3;while(1){x[i]=x0;x0=g(x0);i++;e[i]=x0-PI/3;if(i==16)break;}print1(i);}double g2(double x){return 2*x*cos(x);}void Directiteration2(){cout<<"*******************result of Direct iteration2******************"<<endl;cout<<"初始化x0=PI/3+0.0635232"<<endl;x0=PI/3+0.0635232;int i=0;while(1){x[i]=x0;e[i]=x0-PI/3;x0=g2(x0);i++;if(i==16)break;}print1(i);}double h(double x){return 4*x*(x-PI)/pow(PI,2);}void Directiteration3(){cout<<"*******************result of Direct iteration3******************"<<endl;cout<<"初始化x0=PI/2"<<endl;x0=PI/2;int i=0;while(1){x0=x0-f(x0)/h(x0);e[i]=x0-PI/3;x[i]=x0;i++;if(i==10)break;}print1(i);}int main(){int choice;int tag;while(1){tag=0;do{if(tag!=0)cout<<"Y our choice is illegal!Please input again!"<<endl;tag++;cout<<" =============Menu============="<<endl;cout<<" || 1.Bisection|| ||"<<endl;cout<<" || 2.linearinterpolation ||"<<endl;cout<<" || 3.Nowton Raphson ||"<<endl;cout<<" || 4.Secant ||"<<endl;cout<<" || 5.Direct iteration1 ||"<<endl;cout<<" || 6.Direct iteration2 ||"<<endl;cout<<" || 7.Direct iteration3 ||"<<endl;cout<<" || 8.all of seven ||"<<endl;cout<<" || 9.return ||"<<endl;cout<<" ==============================="<<endl;cout<<" Please input your choice[ ]\b\b";cin>>choice;cout<<endl<<endl;}while(choice<1||choice>9);if(1==choice||8==choice)Bisection();if(2==choice||8==choice)linearinterpolation();if(3==choice||8==choice)NowtonRaphson();if(4==choice||8==choice)Secant();if(5==choice||8==choice)Directiteration1();if(6==choice||8==choice)Directiteration2();if(7==choice||8==choice)Directiteration3();if(9==choice)exit(0);}return 0;}。
一元二次方程求根程序

一元二次方程求根程序一元二次方程是一种常见的数学问题,求解一元二次方程的根是解决这类问题的基础。
在计算机编程中,我们可以编写一个求解一元二次方程根的程序,来简化求解过程,提高效率。
下面我们来介绍一下如何编写一个简单的一元二次方程求根程序。
我们需要了解一元二次方程的一般形式:ax^2 + bx + c = 0,其中a、b、c分别是方程的系数。
为了求解方程的根,我们可以使用求根公式:x = (-b ± √(b^2 - 4ac)) / (2a)接下来,我们可以使用编程语言来实现这个求根公式。
我们以Python语言为例,来编写一个简单的一元二次方程求根程序。
```pythonimport mathdef quadratic_equation(a, b, c):delta = b**2 - 4*a*cif delta < 0:print("该方程无实根")elif delta == 0:x = -b / (2*a)print("该方程有一个实根:", x)else:x1 = (-b + math.sqrt(delta)) / (2*a)x2 = (-b - math.sqrt(delta)) / (2*a)print("该方程有两个实根:", x1, "和", x2)# 测试a = float(input("请输入一元二次方程的a系数:"))b = float(input("请输入一元二次方程的b系数:"))c = float(input("请输入一元二次方程的c系数:"))quadratic_equation(a, b, c)```以上是一个简单的一元二次方程求根程序。
用户可以在程序中输入方程的系数,然后程序会根据输入的系数计算方程的根,并输出结果。
一元两次方程求解

编程求方程ax2+bx+c=0的解,其中的a,b,c由键盘输入。
package一元两次方程;import java.awt.*;import java.awt.event.*;import java.text.DecimalFormat;import javax.swing.*;public class QuadraticEquation {JFrame jframe;JPanel jp1,jp2,jp3;JLabel jl1,jl2,jl3,jl4,jl5,jl6,jl7,jl8;JTextField jt1,jt2,jt3,jt4,jt5;JButton jbtn1,jbtn2,jbtn3;Box box;public void go(){jl1= new JLabel("由键盘输入a、b、c,求一元两次方程 ax2+bx+c=0 的解");jl2 = new JLabel("输入a、b、c:");jl3 = new JLabel("x2 + ");jl4 = new JLabel("x + ");jl5 = new JLabel(" = 0");jl6 = new JLabel("方程 ax2+bx+c=0 的解为:");jl7 = new JLabel("x1=");jl8 = new JLabel(" x2=");jl1.setFont(new Font("Dialog",Font.BOLD,18));jl2.setFont(new Font("Dialog",Font.PLAIN,16));jl3.setFont(new Font("Dialog",Font.PLAIN,16));jl4.setFont(new Font("Dialog",Font.PLAIN,16));jl5.setFont(new Font("Dialog",Font.PLAIN,16));jl6.setFont(new Font("Dialog",Font.PLAIN,16));jl7.setFont(new Font("Dialog",Font.PLAIN,16));jl8.setFont(new Font("Dialog",Font.PLAIN,16));jt1 = new JTextField(5);jt2 = new JTextField(5);jt3 = new JTextField(5);jt4 = new JTextField(6);jt5 = new JTextField(6);jt4.setEditable(false);jt5.setEditable(false);jt4.setBackground(Color.CYAN);jt5.setBackground(Color.CYAN);box = Box.createHorizontalBox();jbtn1 = new JButton(" 求解 ",new ImageIcon("1.png")); box.add(jbtn1);box.add(Box.createHorizontalStrut(30));jbtn2 = new JButton(" 清除 ",new ImageIcon("3.png")); box.add(jbtn2);box.add(Box.createHorizontalStrut(30));jbtn3 = new JButton(" 退出 ",new ImageIcon("2.png")); box.add(jbtn3);jp1 = new JPanel();jp2 = new JPanel();jp3 = new JPanel();jp1.setBackground(Color.WHITE);jp2.setBackground(Color.WHITE);jp1.add(jl1);jp2.add(jl2);jp2.add(jt1);jp2.add(jl3);jp2.add(jt2);jp2.add(jl4);jp2.add(jt3);jp2.add(jl5);jp2.add(jl6);jp2.add(jl7);jp2.add(jt4);jp2.add(jl8);jp2.add(jt5);jp3.add(box);jframe = new JFrame("一元两次方程求解");jframe.add(jp1,BorderLayout.NORTH);jframe.add(jp2,BorderLayout.CENTER);jframe.add(jp3,BorderLayout.SOUTH);jframe.setSize(500, 180);jframe.setLocation(450, 200);jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jframe.setResizable(false);jframe.setVisible(true);/*** 退出按钮注册事件*/jbtn3.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {// TODO自动生成的方法存根System.exit(0);}});/*** 清除按钮注册事件*/jbtn2.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO自动生成的方法存根jt1.setText(null);jt2.setText(null);jt3.setText(null);jt4.setText(null);jt5.setText(null);}});/*** 求解按钮注册事件*/jbtn1.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO自动生成的方法存根if(jt1.getText().length() == 0 || jt2.getText().length() == 0 || jt3.getText().length() == 0){JOptionPane.showMessageDialog(jframe, "任意文本不能为空,请输入a、b、c ! ","警告", JOptionPane.WARNING_MESSAGE);jt1.setText(null);jt2.setText(null);jt3.setText(null);}else{/*把字符串转换成double型*/double a = Double.parseDouble(jt1.getText());double b = Double.parseDouble(jt2.getText());double c = Double.parseDouble(jt3.getText());double x,x1,x2;/*控制输入结果为小数点后面两位*/DecimalFormat df = new DecimalFormat("0.00");if(a==0 && b!=0){x1=x2=-c/b;if(x1==-0.00) {x1 =0.00;x2 =0.00;}jt4.setText(df.format(x1));jt5.setText(df.format(x2));}else if((a!=0) && (b*b-4*a*c>=0)){x1=(-b + Math.sqrt(b*b-4.0*a*c))/(2*a);x2=(-b - Math.sqrt(b*b-4.0*a*c))/(2*a);if(x1>x2){x = x1;x1 = x2;x2 = x;}jt4.setText(df.format(x1));jt5.setText(df.format(x2));}else{JOptionPane.showMessageDialog(jframe, "输入的a、b、c不能构成一元两次方程方程,请重新输入! ","错误", JOptionPane.ERROR_MESSAGE);}}}});}public static void main(String[] args) {// TODO自动生成的方法存根QuadraticEquation qe = new QuadraticEquation();qe.go();}}。
一元二次方程求根JAVA源程序代码

double leftRoot = 0; leftRoot = (- b - Math.sqrt(getDlt())) / (2 * a); return leftRoot; }
public void getRoot() //求解并显示实根或复根的方法 {
public double getB() {
return b; }
public void setC(double c) {
this.c = c; }
public double getC()
{ return c;
} //以上六个方法分别对应三个系数的置取方法
public double getDlt() //计算判别式Δ=b^2-4ac 的值 {
getRightRoot());
}
else //判别式Δ=b^2-4ac<0,方程有两个复根。
{
//double imaginaryNumber1 = 0;
double imaginaryNumber = 0;
double realNumber = 0;
imaginaryNumber = Math.sqrt(-getDlt()) / (2 * a);
double result = Math.pow(b,2) - 4 * a * c; return result; }
private double getRightRoot() //求解右侧较大实根的方法 {
double rightRoot = 0; rightRoot = (-b + Math.sqrt(getDlt())) / (2 * a); return rightRoot; }
实验6-1 计算一元二次方程的根

1.相关知识点 servlet(BeanClass)负责创建生命周期为 request 的 bean 关键代
码是: BeanClass bean=new BeanClass(); Request.setAttribute(“keyWord”,bean);
上述代码会把 bean 存放到 Tomcat 引擎管理的内置对象 pageContext 中,该 bean 被指定的 id 是”keyWord”,scope(生命周期)是 PageContext.REQUEST_SCOPE(request)。 servlet 负责根据模型中数据的变化通知视图(JSP 页面)更新。对 于 scope 是 request 的 bean , 其 手 段 是 使 用 转 发 , 即 使 用 RequestDispatcher 对象向某个 JSP 页面发出请求,让所请求的 JSP 页面显示 bean 中的数据。
} public void setC(double c) {
this.c = c; }
public void setA(double a){ this.a=a;
} public double getA(){
return a; } public void setB(double b){
this.b=b; } public double getB(){
Equation equ=new Equation(); request.setAttribute("equation", equ); double a=Double.parseDouble(request.getParameter("a")); double b=Double.parseDouble(request.getParameter("b")); double c=Double.parseDouble(request.getParameter("c")); equ.setA(a); equ.setB(b); equ.setC(c); if(a!=0)
java一元二次方程求根

java一元二次方程求根Java是一种面向对象的编程语言,可以用来解决各种数学问题。
在本文中,我们将介绍如何用Java编写一个求解一元二次方程根的程序。
一元二次方程是形如ax^2 + bx + c = 0的方程,其中a、b、c 均为实数且a ≠ 0。
方程的解可以用以下公式求得:x = (-b ±√(b^2 - 4ac)) / 2a在Java中,可以使用Math类中的sqrt方法来计算平方根。
以下是求解一元二次方程根的代码示例:import java.util.Scanner;public class QuadraticEquationSolver {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println('请输入一元二次方程的系数:');System.out.print('a=');double a = input.nextDouble();System.out.print('b=');double b = input.nextDouble();System.out.print('c=');double c = input.nextDouble();double discriminant = b * b - 4 * a * c;if (discriminant < 0) {System.out.println('此方程无实数解。
');} else if (discriminant == 0) {double root = -b / (2 * a);System.out.println('此方程有一个实数解:x=' + root);} else {double root1 = (-b + Math.sqrt(discriminant)) / (2 * a); double root2 = (-b - Math.sqrt(discriminant)) / (2 * a); System.out.println('此方程有两个实数解:x1=' + root1 + ',x2=' + root2);}}}在上述代码中,我们首先使用Scanner类获取用户输入的一元二次方程的系数a、b、c。
一元二次方程求根编程
一元二次方程求根编程一元二次方程,这个名字听上去是不是有点吓人?别担心,我们今天就来聊聊它,轻轻松松就能明白。
想象一下,站在数学的舞台上,主角就是这个方程。
我们先说说它的样子。
一般来说,它长得像这样:ax² + bx + c = 0。
嘿,别被这些字母搞晕了,其实它们只是代表一些数字而已。
a、b、c是你心里的小伙伴,x则是我们想要找的“秘密角色”。
咱们的任务,就是揭开这个秘密,找出x的值。
要是这小家伙出现得早,咱们就能轻松搞定方程。
说到求根,心里总是有种兴奋感,像是要揭开一个巨大的谜底。
要解决这个问题,咱们可得用上著名的求根公式。
这个公式像是一把金钥匙,打开了无数的门。
它的样子是这样的:x = (b ± √(b² 4ac)) / (2a)。
听上去有点复杂,但别着急,咱们慢慢来。
咱们得知道b² 4ac这个东西,听起来有点儿高深,其实它是个判别式,决定了方程的根的数量和性质。
要是这个判别式大于零,恭喜你,x有两个不同的值;要是等于零,那就说明x只有一个值,真是缘分啊;要是小于零,咱们的x就不太开心,没得求,变成了虚数,真是让人哭笑不得。
说到这里,有没有觉得数学就像是一场冒险?你永远不知道前方会遇到什么。
就像那些老电影,悬念十足,吸引人。
记得小时候,学数学时总觉得它特别无聊,老师讲的那些公式就像是白开水,喝着喝着都没味道。
但是慢慢地,随着时间的推移,我发现其实它很有趣。
尤其是当我学会了求根公式,突然间,整个世界都亮了起来,像是打开了新天地,原来这不是一场无趣的战斗,而是一次奇妙的旅程。
再说说编程,这也是一件让人又爱又恨的事。
有时候像是在和计算机玩捉迷藏,找来找去,总是找不到那个关键的数字。
可当你成功运行代码,看到输出的结果时,那种成就感真是让人乐开了花。
用编程来解决一元二次方程,就像是在数学的海洋中航行,时而风平浪静,时而波涛汹涌。
把求根公式放进程序里,写上一些简单的逻辑,嘿嘿,瞬间就能得到答案。
一元二次方程求根公式c语言
一元二次方程求根公式c语言一元二次方程的求根公式可以用C语言来实现,代码如下所示:```#include <stdio.h>#include <math.h>int main(){float a, b, c, discriminant, root1, root2;printf("请输入一元二次方程的系数:\n");printf("输入a的值:");scanf("%f", &a);printf("输入b的值:");scanf("%f", &b);printf("输入c的值:");scanf("%f", &c);discriminant = b*b - 4*a*c;if (discriminant > 0){root1 = (-b + sqrt(discriminant)) / (2*a);root2 = (-b - sqrt(discriminant)) / (2*a);printf("方程的两个实根分别为:%.2f 和 %.2f\n", root1, root2);}else if (discriminant == 0){root1 = root2 = -b / (2*a);printf("方程的两个根相同,均为:%.2f\n", root1);}else{float realPart = -b / (2*a);float imaginaryPart = sqrt(-discriminant) / (2*a);printf("方程的两个虚根分别为:%.2f + %.2fi 和 %.2f - %.2fi\n", realPart, imaginaryPart, realPart, imaginaryPart); }return 0;}```这段代码通过用户输入$a$、$b$和$c$的值,然后计算判别式$discriminant=b^2-4ac$的值。
java swing 一元二次方程
AWrongException..javapackage fangcheng;public class AWrongException extends Exception {public AWrongException(String s){super(s);}}Rootx1x2.javapackage fangcheng;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JTextField;public class Rootx1x2 extends JFrame implements RootInterface,ActionListener{ //实现RootInterface double a,b,c, b24ac, x1,x2;String y1,y2;JTextField textA,textB,textC; //数据对象的视图JTextArea roottext;JTextArea showArea; //数据对象的视图JButton button1,button2,button3; //控制器对象Root root;public Rootx1x2(String astr,String bstr,String cstr) throws AWrongException, Exception{ setTitle("求一元二次方程根");setBounds(300,300,150,300);init();setResizable(false);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}void init() throws AWrongException, Exception{root =new Root("0", "0", "0");textA=new JTextField(5);textB=new JTextField(5);textC=new JTextField(5);textA.setText("0");textB.setText("0");textC.setText("0");showArea=new JTextArea();button1= new JButton("求根");button2= new JButton("清空");button3= new JButton("退出");JPanel jp= new JPanel();jp.add(new JLabel("求一元二次方程根"));jp.add(new JLabel("请输入系数a"));jp.add(textA);jp.add(new JLabel("请输入系数b"));jp.add(textB);jp.add(new JLabel("请输入系数c"));jp.add(textC);jp.add(new JLabel("计08-5班X S L"));jp.setFont(new Font("Serif",Font.PLAIN,25));jp.setForeground(Color.pink);roottext = new JTextArea(4,15);String a=null,b=null,c=null;a=textA.getText();b=textB.getText();c=textC.getText();jp.add(button1);jp.add(button2);jp.add(button3);jp.add(roottext);add(jp);button1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {if(Double.valueOf(textA.getText())==0){roottext.setForeground(Color.red);roottext.setText("二次项系数不能为零!");}elseif(root.b24ac(Double.valueOf(textA.getText()),Double.valueOf(textB.getText()),Double.valueOf(textC.getText())) ){root.root_x1x2(Double.valueOf(textA.getText()),Double.valueOf(textB.getText()),Double.valueOf(textC.getroottext.setForeground(new Color(0,50,0));roottext.setText("一元二次方程根为:"+root.getx1()+" , "+root.getx2());}else{root.root_x1x2(Double.valueOf(textA.getText()),Double.valueOf(textB.getText()),Double.valueOf(textC.get Text()));roottext.setForeground(new Color(255,0,0));roottext.setForeground(Color.black);roottext.setText("一元二次方程根为:"+root.gety1()+"+"+root.gety2()+"i");}}});button2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){textA.setText("0");textB.setText("0");textC.setText("0");roottext.setText(null); roottext.setForeground(Color.black);}});button3.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){System.exit(0);}});button1.addActionListener(this);button2.addActionListener(this);button3.addActionListener(this);}public static void main(String[] args) throws AWrongException, Exception{Rootx1x2 r =new Rootx1x2("1","1","1");}public void inputABC(String astr, String bstr, String cstr) throws AWrongException, Exception { // TODO 自动生成方法存根}public boolean b24ac(double a, double b, double c) {// TODO 自动生成方法存根return false;}public void root_x1x2(double a, double b, double c) {// TODO 自动生成方法存根public void actionPerformed(ActionEvent e) {// TODO 自动生成方法存根}}RootInterface.javapackage fangcheng;public interface RootInterface{public void inputABC(String astr,String bstr,String cstr) throws AWrongException, Exception;public boolean b24ac(double a,double b,double c); //求b*b-4*a*cpublic void root_x1x2(double a,double b,double c); //求根}Root.javapackage fangcheng;import java.text.DecimalFormat;public class Root implements RootInterface{ //实现RootInterfacedouble a,b,c, b24ac, x1,x2;String y1,y2;public Root(String astr, String bstr, String cstr) throws AWrongException, Exception{ inputABC(astr,bstr,cstr);root_x1x2(a,b,c);}public double getx1(){return x1;}public double getx2(){return x2;}public String gety1(){return y1;}public String gety2(){return y2;}public void inputABC(String astr,String bstr,String cstr) throws AWrongException, Exception{ a=Double.valueOf(astr);b=Double.valueOf(bstr);c=Double.valueOf(cstr);}public boolean b24ac(double a,double b,double c){b24ac=b*b-4*a*c;if(b24ac>=0&&a!=0)return true;elsereturn false;}public void root_x1x2(double a,double b,double c){DecimalFormat df = new java.text.DecimalFormat("0.00");if( b24ac>=0&&a!=0){x1=Double.valueOf(df.format((-1*b+Math.sqrt(b*b-4*a*c))/(2*a)));x2=Double.valueOf(df.format((-1*b-Math.sqrt(b*b-4*a*c))/(2*a)));}if(b*b-4*a*c<0&&a!=0){y1=String.valueOf(-1*b/(2*a))+'+'+df.format(Math.sqrt(Math.abs(4*a*c-b*b))/(2*a))+'i';y2=String.valueOf(-1*b/(2*a))+'-'+df.format(Math.sqrt(Math.abs(4*a*c-b*b))/(2*a))+'i';}}}。
Java类求解一元二次方程的根
Java类求解⼀元⼆次⽅程的根⼀元⼆次⽅程ax2+bx+c=0,输⼊a,b,c三个系数,求解⽅程,结果有三种情况:两个实数根、⼀个实数根、两个复数根。
/*** Equation.java*/package .uibe.oop;/*** 计算⼀元⼆次⽅程的根* @author TongQiang**/public class Equation {double a,b,c; //⽅程的系数double x1,x2; //两个根double r; //实部double v; //虚部int type; //0表⽰⼀个根,1表⽰两个实根,2表⽰两个复数的根public Equation(double a,double b,double c){this.a = a;this.b = b;this.c = c;}private double delta(){return b*b-4*a*c;}public void calculate(){double d = delta();if(Math.abs(d) < 1E-5){type = 0;x1 = -b/(2*a);x2 = x1;}else if(d > 0){type = 1;x1 = (-b+Math.sqrt(d))/(2*a);x2 = (-b-Math.sqrt(d))/(2*a);}else{type = 2;r = -b/(2*a);v = Math.sqrt(-d)/(2*a);}}public void showResult(){switch(type){case 0:System.out.println("⽅程只有⼀个实根,x1=x2="+x1);break;case 1:System.out.println("⽅程有两个实根,分别是:x1="+x1+"/tx2="+x2);break;case 2:System.out.println("⽅程有两个复数根,分别是:"+r+"+"+v+"i,/t"+r+"-"+v+"i");break;}}public static void main(String[] args) {Equation eq1 = new Equation(1,2,2);eq1.calculate();eq1.showResult();Equation eq2 = new Equation(1,-2,1); eq2.calculate();eq2.showResult();Equation eq3 = new Equation(1,6,5); eq3.calculate();eq3.showResult();}}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
public double getB() {
return b; }
public void setC(double c) {
this.c = c; }
public double getC(){ retu Nhomakorabean c;
} //以上六个方法分别对应三个系数的置取方法
public double getDlt() //计算判别式Δ=b^2-4ac 的值 {
private double getLeftRoot() //求解左侧较小实根的方法 {
double leftRoot = 0; leftRoot = (- b - Math.sqrt(getDlt())) / (2 * a); return leftRoot; }
public void getRoot() //求解并显示实根或复根的方法 {
getRightRoot());
}
else //判别式Δ=b^2-4ac<0,方程有两个复根。
{
//double imaginaryNumber1 = 0;
double imaginaryNumber = 0;
double realNumber = 0;
imaginaryNumber = Math.sqrt(-getDlt()) / (2 * a);
realNumber
= -getB() / (2 * a);
System.out.println("一元二次方程:" + getA() + "x^2+"
+ getB() + "x+"
+ getC() + "\t 有两个复根:"
+ realNumber + "±" + imaginaryNumber + "i");
+ getC() + "\t 有唯一解:" + result);
}
else if(getDlt()>0) //判别式Δ=b^2-4ac>0,方程有两个相异实根。
{
System.out.println("一元二次方程:" + getA() + "x^2+"
+ getB() + "x+"
+ getC() + "\t 有两个实根:" + getLeftRoot() + "和" +
this.a = a; this.b = b; this.c = c; }
//有参构造方法
public void setA(double a) {
this.a = a; }
public double getA() {
return a; }
public void setB(double b) {
this.b = b; }
double result = 0;
result = -getC() / getB();
System.out.println("一元二次方程:" + getA() + "x^2+"
+ getB() + "x+"
+ getC() + "\t 有唯一解:" + result);
}
}
else //二次项系数不为零,方程有两个实根或复根。
if(a==0) {
if(b==0) {
if(c==0) {
System.out.println("一元二次方程:" + getA() + "x^2+" //a、b、c 全为零时,定义方程有无 穷多解。
+ getB() + "x+" + getC() + "\t 有无穷多解。"); } else { //二次项和一次项系数为零,但常数项不为零,方程变为不等式,无解。 System.out.println("一元二次方程:" + getA() + "x^2+" + getB() + "x+" + getC() + "\t 无解。"); } } else { //二次项系数为零,一次项系数不为零,方程是一次方程,有唯一解。
}
}
}
}
public class Test {
public static void main(String [] args) {
OnceBasicQuadraticEquation e1 = new OnceBasicQuadraticEquation(4,13,3); e1.getRoot();
} }
//求解一元二次方程 ax^2+bx+c=0 的实根和复根,Test 类是主类
class OnceBasicQuadraticEquation //求解一元二次方程 ax^2+bx+c 的实根和复根的类,其中 getRoot()方法求根和显
示根
{
private double a;
//方程的二次项系数
private double b;
//方程的一次项系数
private static double c; //方程的常数项
//以上三个成员变量分别是方程的系数
OnceBasicQuadraticEquation() {
a = 0; b = 0; c = 0; }
//无参构造方法
OnceBasicQuadraticEquation(double a,double b,double c) {
double result = Math.pow(b,2) - 4 * a * c; return result; }
private double getRightRoot() //求解右侧较大实根的方法 {
double rightRoot = 0; rightRoot = (-b + Math.sqrt(getDlt())) / (2 * a); return rightRoot; }
{
if(getDlt()==0) //判别式Δ=b^2-4ac=0,方程有两个相等实根。
{
double result = 0;
result = -getB() / (2 * getA());
System.out.println("一元二次方程:" + getA() + "x^2+"
+ getB() + "x+"