一元二次方程的因式分解
/**
* 求因式分解
* @author tiger
* @date 2010-08-23
*/
public class fenjie {
public int a ;
public int b ;
public int c ;
public void print()
{
String str = "";
if(a == 1)
{
str += "x^2";
}
else if(a > 0 || a < 0)
{
str += a + "x^2";
}
if(b == 1)
{
str += " + " + "x" ;
}
else if(b > 0)
{
str += " + " + b + "x" ;
}
else if(b < 0)
{
str += " - " + (-b) + "x";
}
if(c > 0)
{
str += " + " + c;
}
else if(c < 0)
{
str += " - " + (-c);
}
str += " = ";
int one = b * b - 4 * a * c;
if(one < 0)
{
str += "不能因式分解";
}
if(one == 0)
{
double two = -b / (2 * a);
if(two > 0)
{
str += "(x - " + two + ") ^ 2" ;
}
else if(two < 0)
{
str += "(x + " + (-two) + ") ^ 2";
}
else if(two == 0)
{
double sqrt = Math.sqrt(a);
str += "(" + sqrt + "x) ^ 2";
}
}
else if(one > 0)
{
double sqrt = Math.sqrt(one);
double two1 = (-b + sqrt) / (2 * a);
double two2 = (-b - sqrt) / (2 * a);
//第一个因式
if(two1 > 0)
{
str += "(x - " + two1 + ")" ;
}
else if(two1 < 0)
{
str += "(x + " + (-two1) + ")";
}
else if(two1 == 0)
{
str += "(x)";
}
//第二个因式
if(two2 > 0)
{
str += "(x - " + two2 + ")" ;
}
else if(two2 < 0)
{
str += "(x + " + (-two2) + ")";
}
else if(two2 == 0)
{
str += "(x)";
}
}
System.out.println(str);
}
public static void main(String[] args) {
fenjie f = new fenjie();
f.a = 1;
f.b = 3;
f.c = -4;
f.print();
}
}
/*
*
打印结果:
x^2 + 3x - 4 = (x - 1.0)(x + 4.0)
*/