我有一个听起来像这样的练习:
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");
}
}
}
}
假设 if
、else 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/