# 一元二次方程(aX^2+bX+C=0)的求根时,没有实根,用复数表示根???

xia105711 2010-10-12 10:03:15

...全文
1150 点赞 收藏 6

6 条回复

zhangjie127616 2011-03-10
/**求解一元二次方程: ax2+bx+c=0*/
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);
}
}
}

xia105711 2010-10-13
[Quote=引用 3 楼 wangerjun888 的回复:]

[/Quote]

wangerjun888 2010-10-13

kebin0001 2010-10-12

``````
public static void main(String[] args) {
double a = 1D;
double b = 6D;
double c = 25D;

double e = b * b - 4 * a * c;
if (e < 0) {
System.out.println(-b/(2*a) + " + " + Math.sqrt(-e)/(2*a)+"i");
System.out.println(-b/(2*a) + " - " + Math.sqrt(-e)/(2*a)+"i");
} else {
System.out.println((-b + Math.sqrt(e)) / (2 * a));
System.out.println((-b - Math.sqrt(e)) / (2 * a));
}
}
``````

J2ME

1.3w+

Java J2ME

2010-10-12 10:03