java - 如何在不相乘的情况下验证 3 个数字的乘积的符号?

标签 java

我有一个听起来像这样的练习:

Calculate the sign of the product of 3 numbers:

  • Read 3 floating-point numbers
  • Print the sign of the product of the entered 3 numbers: positive, negative or zero

Try to do this without multiplying the 3 numbers

我尝试过这种方式:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

       Scanner in = new Scanner(System.in);

       double a = in.nextDouble();
       double b = in.nextDouble();
       double c = in.nextDouble();


       switch(){
          case a:
          case b:
          case c:
             if (a > 0 && b > 0 && c > 0){
                System.out.printf("positive");
             }else if ( a > 0 && b < 0 && c > 0){
                System.out.printf("negative");
             }else if ( a > 0 && b > 0 && c < 0){
                System.out.printf("negative");
             }else if ( a < 0 && b > 0 && c > 0){
                System.out.printf("negative");
             }else if ( a == 0 && b == 0 && c == 0){
                System.out.printf("zero");
             }
       }


}

}

假设 ifelse if 条件正确,我应该在 switch 的括号中放入什么条件才能使该程序正常工作?

如果不是,我可以用 switch case 做什么来成功解决这个练习?

我的输入例如:

2
3
-1

我的输出:

negative

最佳答案

考虑所有 3 个数字均非零

如果有 1 或 3 个负数,则乘积将为负数。否则,产品将为正。

int count = 0;
if(a < 0)
    count++;
if(b < 0)
    count++;
if(c < 0)
    count++;

if(count % 2 == 1)
    System.out.println("Negative");
else
    System.out.println("Positive");

关于java - 如何在不相乘的情况下验证 3 个数字的乘积的符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60248344/

相关文章:

java - 如何使用突出显示的最短路径编码从源到目的地的多种可能路线

java - 将多个 BufferedImages 叠加在一起?

java - 如何检查 String[] 类型的页面属性?

java - 初学者 JavaFX,跟踪随机生成的最大半径?

Java、泛型和 PECS : still having trouble understanding the C part; concrete example?

java - 平移/旋转/移动图形对象而不弄乱整个屏幕

java - Vaadin 和自定义 Gwt Widget - 设置小部件语言

java - 如何调用某个类的方法(继承)

java - 读取 GoogleSignIn 的 awsconfiguration.json 时出错

java - 由于内存不足错误导致 cassandra 意外关闭