所以我不得不用Java编写一个程序来使用二次公式求解“x”的值,这包括虚数和实数。问题是我的代码似乎没有为以下 3 个值提供正确的结果:
a=10,000
b=75,000
c=35,000
但是,它会为小整数返回正确的值。知道为什么吗?我认为这与 double 的数据类型有关,但我不确定。
请注意,要求包括输入只能是整数类型
我相信正确的结果是 -7.0 和 -0.5,但我收到的是虚构的结果。谢谢
这是我的代码:
package QuadRootsInt;
import java.util.Scanner;
/**
*
* @author
*/
public class QuadRootsInt {
/**
* Instance variables
*/
private double realNumb;
private double imagNumb;
private double finalRoot1;
private double finalRoot2;
/**
*
* @param a a value of binomial
* @param b b value of binomial
* @param c c value of binomial
*/
public QuadRootsInt(int a, int b, int c){
if(a==0){
System.out.println("Cannot divide by zero...system is exisitng.");
System.exit(0);
}
}
/**
* Evaluating the square root part of the formula and updates the right variable accordingly
* @param a first coefficient of binomial
* @param b second coefficient of binomial
* @param c third coefficient of binomial
*/
public void getRoot(int a, int b, int c){
if((b*b)<4*a*c){
imagNumb=Math.sqrt(Math.abs(Math.pow(b,2)-4*a*c));
double realFinal1=((-b)/(2.0*a));
double imagFinal1=(imagNumb/(2.0*a));
double realFinal2=((-b)/(2.0*a));
double imagFinal2=(imagNumb/(2.0*a));
System.out.println("The solutions to the quadratic are: " + realFinal1+"+"+"i"+imagFinal1 + " and " + realFinal2+"-"+"i"+imagFinal2);
}
else {
realNumb=Math.sqrt(Math.pow(b, 2)-4*a*c);
finalRoot1=((-b)+realNumb)/(2*a);
finalRoot2=((-b)-realNumb)/(2*a);
System.out.println("The solutions to the quadratic are: " + finalRoot1 + " and " + finalRoot2);
}
}
/**
* Main Method - Testing out the application
* @param args
*/
public static void main(String args[]){
Scanner aCoef = new Scanner(System.in);
System.out.print("Enter the 'a' coefficient: ");
int aInput = aCoef.nextInt();
Scanner bCoef = new Scanner(System.in);
System.out.print("Enter the 'b' coefficient: ");
int bInput = bCoef.nextInt();
Scanner cCoef = new Scanner(System.in);
System.out.print("Enter the 'c' coefficient: ");
int cInput = cCoef.nextInt();
QuadRootsInt quadTest = new QuadRootsInt(aInput, bInput, cInput);
quadTest.getRoot(aInput, bInput, cInput);
}
}