最小和最大的输入 [英] smallest and largest of the inputs
本文介绍了最小和最大的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我被分配编写一个程序,读取一系列整数输入并打印
-输入中最小和最大的
-以及偶数和奇数输入的数量
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);
}
推荐答案
最简单的解决方案是使用类似 Math.min
和 Math.max
The simplest solution would be use something like Math.min
and 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);
}
这篇关于最小和最大的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文