检查是否除以零,然后打印两行?

时间:2016-02-16 00:12:58

标签: java if-statement divide-by-zero infinity

我正在尝试编写一个程序,它将接受两个用户输入数字,然后根据它们执行计算,但我想使用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

2 个答案:

答案 0 :(得分:1)

这里似乎有多个问题。这里的第一个问题是你在决定是否解决方案时检查分子。例如,如果输入1和0,则代码会检查是否为&gt; 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 */
    }
  }
}

答案 1 :(得分:0)

因为我注意到你试图从控制台获取一个整数为double。这可能导致各种奇怪的输出。  所以将代码更改为

tbl_finance_invoice_paid_items

这应该可以正常工作。 THANKYOU