我怎样才能做到这一点,如果用户输入 0,则输出行表示你不能在 java 中除以零
How can i make it so that if user inputs 0 a output line says that you cannot divide by zero in java
我试图让 "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");
}
}
}
您需要将 if(a == 0)
检查放在查看 dis 的检查之前。
我试图让 "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");
}
}
}
您需要将 if(a == 0)
检查放在查看 dis 的检查之前。