我试图不让“a”的用户输入为 0,因为这会导致等式除以零,从而输出错误,我将能够有一个 println 说你不能除以零,如果用户为“a”输入 0 这是我的代码,我不确定我做错了什么,我还是新手,只需要帮助:
import java.util.Scanner;
class a3main{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the value of a");
int a = keyboard.nextInt();
System.out.println("Enter the value of b");
int b = keyboard.nextInt();
System.out.println("Enter the value of c");
int c = keyboard.nextInt();
double R1, R2, dis;
dis = b * b - 4 * a * c; // This is the discriminant formula
if(dis > 0 )
{
System.out.println("The roots are both real numbers and unequal");
R1 = (-b + Math.sqrt(dis))/(2*a);
System.out.println("The first root is: " + R1);
R2 = (-b - Math.sqrt(dis))/(2*a);
System.out.println("The second root is: " + R2);
}
else if(dis == 0)
{
System.out.println("The roots are both equal and are equal");
R1 = (-b + Math.sqrt(dis))/(2*a);
System.out.println("The root is: " + R1);
}
else if (a == 0)
{
System.out.println("You cannot divide by 0");
}
else
{
System.out.println("The roots are imaginary");
}
}
}