五个数字中最大的一个



我的家庭作业有问题。我的程序必须适用于整数和浮点数。

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
int d=sc.nextInt();
int e=sc.nextInt();
if ((a >= b) && (a >= c) && (a >= d) && (a >= e)) { // a >= b,c,d,e
System.out.println (a);
} else if ((b >= c) && (b >= d) && (b >= e)) {      // b >= c,d,e
System.out.println ( b);
} else if ((c >= d) && (c >= e)) {                  // c >= d,e
System.out.println ( c);
} else if (d >= e) {                                // d >= e
System.out.println ( d);
} else {                                            // e > d
System.out.println (e);
}
}

代码出了什么问题?

如果它必须适用于int"浮点"数,那么您应该对所有五个值使用Scannet.nextDouble()(它们应该是double(。也就是说,int具有浮点分量。类似

Scanner sc = new Scanner(System.in);
double a = sc.nextDouble(), b = sc.nextDouble(), c = sc.nextDouble(),
d = sc.nextDouble(), e = sc.nextDouble();
System.out.println(Math.max(Math.max(Math.max(Math.max(a, b), c), d), e));

您可以将List与Collections类一起使用。但不确定这是否在你的作业参数范围内。

public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
List<Double> nums = new ArrayList<>();
for(int x = 0; x < 5; x++)
{
nums.add(sc.nextDouble());
}
System.out.println("The biggest number entered is " + Collections.max(nums));
}

最新更新