[英]How to Pass This Test Case?
I'm creating the program that determines the largest and smallest number is a series of numbers entered by the user.我正在创建确定最大和最小数字的程序是用户输入的一系列数字。 I've created several tests cases for my code and they all work out, but it fails the most simple test case.
我为我的代码创建了几个测试用例,它们都成功了,但它在最简单的测试用例中失败了。 When the user inputs a single number.
当用户输入单个数字时。 For instance, if the user sets the terminating value to be 25, then enters -1, and finally enters the terminating the value, the output should be Largest: -1 and Smallest: -1.
例如,如果用户将终止值设置为25,然后输入-1,最后输入终止值,则输出应为Largest:-1 和Smallest:-1。 However, my code will output Largest: 0 and Smallest: -1 -- I why this happens (because I initialized the max value to be 0 before running the loop), but how can I fix this?
但是,我的代码将输出 Largest: 0 和 Smallest: -1 -- 我为什么会发生这种情况(因为我在运行循环之前将最大值初始化为 0),但是我该如何解决这个问题?
Here's my code...这是我的代码...
Scanner scan = new Scanner(System.in);
// Declaration variables
double min;
double max = 0;
System.out.println("Enter terminating number: ");
double terminator = scan.nextDouble();
System.out.println("Enter a number: ");
double num = scan.nextDouble();
min = num;
if (num == terminator) {
System.out.println("There must be one number in the list.");
// break;
} else {
while (num != terminator) {
System.out.println("");
num = scan.nextDouble();
if ((num < min) && (num != terminator)) {
double temp = min;
min = num;
max = temp;
} else if ((num > min) && (num != terminator)) {
max = num;
} else {
max = min;
}
}
System.out.println("Largest: " + max);
System.out.println("Smallest: " + min);
}
Instead of initializing max = 0
, do max = num
just like you already do with min
.不要初始化
max = 0
,而是像你已经对min
做的那样做max = num
。
It's not clear why you're initializing max
differently from min
;不清楚为什么你初始化
max
与min
不同; when a single number has been entered, it's both the minimum and the maximum.当输入单个数字时,它既是最小值又是最大值。 Right now, the only code that modifies
max
is within the loop that reads numbers beyond the first, so the first number has no effect on it.现在,修改
max
的唯一代码是在循环中读取第一个数字以外的数字,因此第一个数字对其没有影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.