java 最小和最大输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15328779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
smallest and largest of the inputs
提问by Aniki
I was assigned to write a program that read a sequence of integer inputs and print -the smallest and largest of the inputs -and the number of even and odd inputs
我被指派编写一个程序,读取一系列整数输入并打印 - 最小和最大输入 - 以及偶数和奇数输入的数量
I figured out the first part but am stumped on how I can get my program to display the largest and the smallest. This is my code so far. How can I get it to display the smallest input aswell?
我想出了第一部分,但对如何让我的程序显示最大和最小的程序感到困惑。到目前为止,这是我的代码。我怎样才能让它显示最小的输入?
public static void main(String args[])
{
Scanner a = new Scanner (System.in);
System.out.println("Enter inputs (This program calculates the largest input):");
double largest = a.nextDouble();
while (a.hasNextDouble())
{
double input = a.nextDouble();
if (input > largest)
{
largest = input;
}
}
System.out.println(largest);
}
回答by MadProgrammer
The simplest solution would be use something like Math.min
and Math.max
最简单的解决方案是使用类似Math.min
和Math.max
double largest = a.nextDouble();
double smallest = largest;
while (a.hasNextDouble()) {
double input = a.nextDouble();
largest = Math.max(largest, input);
smallest = Math.min(smallest, input);
}
回答by Etienne Miret
double largest = a.nextDouble();
double smallest = largest;
while (a.hasNextDouble()) {
double input = a.nextDouble();
if (input > largest) {
largest = input;
}
if (input < smallest) {
smallest = input;
}
}
回答by Alden
Keep track of the smallest value in the same manner.
以相同的方式跟踪最小值。
public static void main(String args[])
{
Scanner a = new Scanner (System.in);
System.out.println("Enter inputs (This program calculates the largest and smallest input):");
double firstInput = a.nextDouble();
double largest = firstInput;
double smallest = firstInput;
while (a.hasNextDouble())
{
double input = a.nextDouble();
if (input > largest)
{
largest = input;
}
if (input < smallest)
{
smallest = input;
}
}
System.out.println("Largest: " + largest);
System.out.println("Smallest: " + smallest);
}
}