分享

Java学习——95.解一元二次方程

 pythonjava学习 2021-04-06

一元二次方程,即数学里如下形式的方程:

其计算结果为:

公式虽然好背,但实际计算时,反正我读初高中的时候很讨厌的,总是算不对,但是学了Java后发现,真是不难啊,写代码比计算这样的方程式简单多了。只需写一次,要计算的时候直接运行就行了。

其代码如下:

import java.util.*;

public class yiyuan {

public static void main(String args[]) {

    Scanner sc=new Scanner(System.in);

    System.out.print("请输入系数a:");

    double a=sc.nextDouble();

    System.out.print("请输入系数b:");

    double b=sc.nextDouble();

    System.out.print("请输入系数c:");

    double c=sc.nextDouble();

    double x1=(-b+Math.sqrt(Math.pow(b, 2)-4*a*c))/(2*a);

    double x2=(-b-Math.sqrt(Math.pow(b, 2)-4*a*c))/(2*a);

    System.out.println("x1="+x1+",x2="+x2);

    sc.close();

    }

}

其运行结果如下:

也可改成图形用户界面,用得更加得心应手,只是在第一次写的时候花点时间。

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

//y=a^2+b*x+c

public class yiyuan extends JFrame implements ActionListener{

private static final long serialVersionUID = 1L;

private JTextField a,b,c;

private JButton button;

private JTextArea text;

public yiyuan() {

    super("求解一元二次方程");

    this.setVisible(true);

    this.setSize(240,240);

    this.setLocation(200,200);

    JPanel p=new JPanel();

    JLabel label1=new JLabel("求一元二次方程:ax^2+bx+c=0的值");

    JLabel label2=new JLabel("这里的^表示乘方");

    label2.setForeground(Color.blue);

    p.add(label1);

    p.add(label2);

    this.getContentPane().add(p,"North");

    JPanel p1=new JPanel();

    p1.add(new JLabel("请输入系数a:"));

    a=new JTextField(10);

    p1.add(a);

    p1.add(new JLabel("请输入系数b:"));

    b=new JTextField(10);

    p1.add(b);

    p1.add(new JLabel("请输入系数c:"));

    c=new JTextField(10);

    p1.add(c);

    button=new JButton("计算");

    button.addActionListener(this);

    p1.add(button,"");

    this.getContentPane().add(p1);

    text=new JTextArea();

    this.getContentPane().add(text,"South"); 

}

public static void main(String args[]) {

    new yiyuan();

}

@Override

public void actionPerformed(ActionEvent arg0) {

// TODO Auto-generated method stub

    double ax,bx,cx;

    if(a.getText().equals("")||b.getText().equals("")||c.getText().equals("")) {

        text.setText("请输入系数");

        text.setForeground(Color.red);

}

    else {

    ax=Double.parseDouble(a.getText());

    bx=Double.parseDouble(b.getText());

    cx=Double.parseDouble(c.getText());

    double x1=(-bx+Math.sqrt(Math.pow(bx, 2)-4*ax*cx))/(2*ax);

    double x2=(-bx-Math.sqrt(Math.pow(bx, 2)-4*ax*cx))/(2*ax);

    text.setForeground(Color.black);

    text.setText("方程"+a.getText()+"x^2+"+b.getText()+"x+"+c.getText()+"的值为:\nx1="+x1+"\nx2="+x2);

a.setText("");

    b.setText("");

    c.setText("");

    }

     }

}

其运行结果如下:

如果输入的时候为空,会有提示:

也会存在没有解的情况,如:

因为在程序中,计算的动作事件中设置了将三个文本框中的数据清空,所以本图中的三个文本框为空。

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多