我正在尝试编写一个程序,该程序将使用两个用户输入数字,然后根据它们进行计算,但是我想使用if语句检查它是否试图除以零或输出将是无穷大。

import java.util.Scanner;

public class work {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

double a, b, c, d;
System.out.printf("Enter the first number:");
a = scan.nextDouble();

System.out.printf("Enter the second number:");
b = scan.nextDouble();

/* various calculations  */
c = a / b;
d = b / a;


if (a > 0)
     {
System.out.printf("a/b = %.2f\n", c);
     }
if (b > 0)
{  System.out.printf("b/a = %.2f\n", d);
}

else if (a <= 0)
{  System.out.printf("a/b = %.1f\n", d);
    if (b > 0)
        System.out.printf("a/b = INF\n");
}
}
}


因此,例如,如果我输入4和5,它将最终像这样:

Enter the first number: 4
Enter the second number: 5
a/b = 0.80
b/a = 1.25


但是,我很难让它检查零,并最终产生许多奇怪的输出。我如何获得这样的输出?

------ Sample run 2:
Enter the first number: 0
Enter the second number: 4
a/b = 0.0
b/a = INF

------ Sample run 3:
Enter the first number: 4
Enter the second number: 0
a/b = INF
b/a = 0.0

------ Sample run 4:
Enter the first number: 0
Enter the second number: 0
a/b = INF
b/a = INF

最佳答案

似乎您在这里有多个问题。您的第一个问题是,在确定解决方案是INF时要检查分子。例如,如果您输入1和0,则您的代码将检查a> 0(它是否为0)并输出c / 1/0。您真正想要做的是检查等式(在本例中为b)的控制者是否等于零。

看来您也忘记了第一个if语句上的else语句,但不确定第二个if语句中else语句要完成什么。

第三个问题是您的代码正在检查变量是否小于0,而不是不等于0,这将在输入为负数时产生意外结果。请记住,只有零会导致答案不确定,也就是您所称的INF。无论如何,下面的代码应按预期运行。请注意,我已经稍微修改了类名以符合Java naming conventions

import java.util.Scanner;

public class Work {

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    double a, b, c, d;
    System.out.print("Enter the first number: ");
    a = scan.nextDouble();

    System.out.print("Enter the second number: ");
    b = scan.nextDouble();

    /* various calculations  */
    c = a / b;
    d = b / a;


    if (b != 0)
    {
      System.out.printf("a/b = %.2f\n", c); /* the dominator (b) is not
                                             zero, so the solution is a/b
                                             (stored in the variable c) */
    }
    else
    {
      System.out.print("a/b = INF\n"); /* the dominator (b) is zero,
                                        so the solution is INF */
    }

    if (a != 0)
    {
      System.out.print("b/a = %.2f\n", d); /* the dominator (a) is not
                                            zero, so the solution is a/b
                                            (stored in the variable d) */
    }
    else
    {
      System.out.printf("b/a = INF\n"); /* the dominator (a) is zero,
                                         so the solution is INF */
    }
  }
}

08-18 14:43
查看更多