这是我的代码,通过从用户那里获取5个输入来显示最小和最大整数...它适用于最小值但不适用于最大值而我无法找出问题...请帮助
import java.util.Scanner;
public class LargestAndSmallestIntegers {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int a,b,c,d,e;
int small,large;
System.out.println("Enter five integer values...");
a=input.nextInt();
small=a;
large=a;
b=input.nextInt();
if (small<b)
{
large=b;
}
else
{
small=b;
}
c=input.nextInt();
if (small<c)
{
large=c;
}
else
{
small=c;
}
d=input.nextInt();
if (small<d)
{
large=d;
}
else
{
small=d;
}
e=input.nextInt();
if (small<e)
{
large=e;
}
else
{
small=e;
}
input.close();
System.out.printf("%d is smallest and %d is largest", small,large);
}
}
答案 0 :(得分:1)
private int a = input.nextInt(),
b = input.nextInt(),
c = input.nextInt(),
d = input.nextInt(),
e = input.nextInt();
private int small, large;
small = min(a,b);
small = min(small,c);
small = min(small,d);
small = min(small,e);
large = max(a,b);
large = max(large,c);
large = max(large,d);
large = max(large,e);
private int min(int a, int b) {
if (a < b) return a else return b;
}
private int max(int a, int b) {
if (a > b) return a else return b;
}
我认为这有效;)
答案 1 :(得分:0)
它适用于最小值但不适用于最大值
正如lared指出的那样,与small
进行比较以确定large
是有缺陷的。您必须在比较逻辑中包含类似的内容:
if (large < b)
{
large = b;
}
除了您现有的比较:
if (small > b)
{
small = b;
}
答案 2 :(得分:-1)
你总是只检查最小值。你还需要检查
if (small<e)
{
if(large < e)
{
large=e;
}
}