Java 在3个数字内找到第二个最小值
我收到了关于以下问题的作业: 这个问题要求我找到三个数字中的第二个最小值,但不使用以下内容:Java 在3个数字内找到第二个最小值,java,algorithm,sorting,math,Java,Algorithm,Sorting,Math,我收到了关于以下问题的作业: 这个问题要求我找到三个数字中的第二个最小值,但不使用以下内容: if-else statements, ternary operators or loops 在Math.max和Math.min的帮助下 此外,除了Scanner类之外,我无法导入任何内容 这就是我到目前为止所做的: Scanner N = new Scanner(System.in); int a, b, c, sec; System.out.print("Enter three numbers.
if-else statements, ternary operators or loops
在Math.max和Math.min的帮助下
此外,除了Scanner类之外,我无法导入任何内容
这就是我到目前为止所做的:
Scanner N = new Scanner(System.in);
int a, b, c, sec;
System.out.print("Enter three numbers.\n> ");
a = N.nextInt();
b = N.nextInt();
c = N.nextInt();
sec=(a>b)? (b>c)? b : c : (a>c)? a : c;
System.out.print(sec);
通过从三个数字的总和中减去最小值和最大值,可以得到第二小的数字。假设三个数字是a、b和c
通过从三个数字的总和中减去最小值和最大值,可以得到第二小的数字。假设三个数字是a、b和c 给定三个数字a、b和c,您可以在一行代码中获得第二个最小值:
int second = Math.max(Math.min(a,b), Math.min(Math.max(a,b),c));
请注意,它仅使用Math.min和Math.max来完成任务。
它甚至不使用加减法
下面是一个测试用例:
给定三个数字a、b和c,您可以在一行代码中获得第二个最小值:
int second = Math.max(Math.min(a,b), Math.min(Math.max(a,b),c));
请注意,它仅使用Math.min和Math.max来完成任务。
它甚至不使用加减法
下面是一个测试用例:
另一个解决方案是将数字添加到数组中并对其进行排序。索引1处的数字是第二小的
public static void main(String[] args) {
Scanner N = new Scanner(System.in);
int[] numbers = new int[3];
System.out.print("Enter three numbers.\n> ");
numbers[0] = N.nextInt();
numbers[1] = N.nextInt();
numbers[2] = N.nextInt();
Arrays.sort(numbers);
System.out.print(numbers[1]);
}
另一个解决方案是将数字添加到数组中并对其进行排序。索引1处的数字是第二小的
public static void main(String[] args) {
Scanner N = new Scanner(System.in);
int[] numbers = new int[3];
System.out.print("Enter three numbers.\n> ");
numbers[0] = N.nextInt();
numbers[1] = N.nextInt();
numbers[2] = N.nextInt();
Arrays.sort(numbers);
System.out.print(numbers[1]);
}
我们不是来帮你做作业的。请发布你到现在为止尝试过的东西好吧,我已经用if-else语句完成了这个程序,但问题禁止我这么做that@weakit展示给我们看。你可以用max和min做很多事情,特别是当你只有3个数字需要担心的时候。你有没有尝试过以任何方式组合它们?提示:最小=最小,最大=最大。还有什么?我们不是来帮你做作业的。请发布你到现在为止尝试过的东西好吧,我已经用if-else语句完成了这个程序,但问题禁止我这么做that@weakit展示给我们看。你可以用max和min做很多事情,特别是当你只有3个数字需要担心的时候。你有没有尝试过以任何方式组合它们?提示:最小=最小,最大=最大。还有什么?