编写一个java程序,从键盘输入一元二次方程的3个系数a,b和c,输出这个方程的解

如题所述

import javax.swing.JOptionPane;
public class quadratic_Equation
{
public static void main(String[ ] args)
{
double a, b, c, D, x1, x2 ;
String string_a, string_b, string_c, result;
String answer=" ";
string_a = JOptionPane. showInputDialog("输入方程中的二次项系数");
a = Double.parseDouble(string_a);
string_b = JOptionPane. showInputDialog("输入方程中的一次项系数");
b = Double.parseDouble(string_b);
string_c = JOptionPane. showInputDialog("输入方程的常数项");
c = Double.parseDouble(string_c);
D = b*b-4*a*c; // 计算根的判别式
if( D > 0 ){ // 有二个不相等的实数解
x1=(- b+Math.sqrt(D))/( 2*a );
x2=(- b-Math.sqrt(D))/( 2*a );
JOptionPane.showMessageDialog(null, "方程"+a+" x*x+"+b+"x +" +c+" =0的解为:x1="+x1+", x2="+x2,"解方程", JOptionPane.INFORMATION_MESSAGE);
}
if( D == 0 ){ // 有二个相等的实数解
x1 = x2 = -b / ( 2*a );
JOptionPane.showMessageDialog(null, "方程"+a+" x*x+"+b+"x +"+c+" =0的解为:x1=x2="+x1, "解方程", JOptionPane.INFORMATION_MESSAGE);
}
if( D < 0 ){ // 无实数解
double r = -b / (2 * a);
double i = Math.sqrt(4 * a * c - b * b) / (2 * a);
answer = "X1= " + r + "+ " + i + "i X2= " + r + "- " + i + "i ";
JOptionPane.showMessageDialog(null, "方程"+a+" x*x+"+b+"x +" +c+" =0的复数解为:"+answer ,"解方程", JOptionPane.INFORMATION_MESSAGE);
}
}
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2018-03-02
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int a=input.nextInt();
    int b=input.nextInt();
    int c=input.nextInt();
    int x = 0;
    while(true){
        if(a*x+b*x*x+c==42){
            System.out.println("解得: x="+x);
            break;
        }
        x=x+1;
    }
}

这个就是个强行拿一个个数字去套这个方程,成功,即返回结果,如果方程无解,那这就是个死循环了。不清楚这题考的知识点,我猜想应该是考循环,所以这么写的答案,不见得正确。另外,Java中平方可以用Math.pow(x,2)来表示x的平方。

相似回答