
用Java编写一程序,求解一元二次方程:aX2+bX+c=0。参数a、b及c从命令行做参数输入
3个回答
展开全部
public static main(String[] arg0){
if(arg0== null || arg0.length == 0){
System.out.println("请输入参数:a,b,c");
System.exit(0);
}
for(int i=0;i<arg0.length;i++){
try {
Float.parseFloat(arg0[i]);
} Catch(Exception e){
System.out.println("请输入数字");
System.exit(0);
}
}
float a = Float.parseFloat(arg0[0]);
float b = 0;
float c = 0;
if(arg0.length >= 2){
b = Float.parseFloat(arg0[1]);
}
if(arg0.length >= 3){
c = Float.parseFloat(arg0[2]);
}
float tmp = b*b - 4*a*c;
if(tmp < 0 ){
System.out.println("x无实数根");
System.exit(0);
}
if(a==0 && b==0 && c==0){
System.out.println("x有任意实数根");
System.exit(0);
}
float result = (-1)*b/(2*a);
if(tmp == 0){
System.out.println("x1=x2="+result);
System.exit(0);
}
float x1 = ((-1)*b+java.lang.Math.sqrt(tmp))/(2*a);
float x2 = ((-1)*b-java.lang.Math.sqrt(tmp))/(2*a);
System.out.println("x1="+x1);
System.out.println("x2="+x2);
}
if(arg0== null || arg0.length == 0){
System.out.println("请输入参数:a,b,c");
System.exit(0);
}
for(int i=0;i<arg0.length;i++){
try {
Float.parseFloat(arg0[i]);
} Catch(Exception e){
System.out.println("请输入数字");
System.exit(0);
}
}
float a = Float.parseFloat(arg0[0]);
float b = 0;
float c = 0;
if(arg0.length >= 2){
b = Float.parseFloat(arg0[1]);
}
if(arg0.length >= 3){
c = Float.parseFloat(arg0[2]);
}
float tmp = b*b - 4*a*c;
if(tmp < 0 ){
System.out.println("x无实数根");
System.exit(0);
}
if(a==0 && b==0 && c==0){
System.out.println("x有任意实数根");
System.exit(0);
}
float result = (-1)*b/(2*a);
if(tmp == 0){
System.out.println("x1=x2="+result);
System.exit(0);
}
float x1 = ((-1)*b+java.lang.Math.sqrt(tmp))/(2*a);
float x2 = ((-1)*b-java.lang.Math.sqrt(tmp))/(2*a);
System.out.println("x1="+x1);
System.out.println("x2="+x2);
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询