这是我在CodingBat上看到的问题:
给定2个正的int值,返回10..20(含)范围内的较大值,如果两者都不在该范围内,则返回0。
这是我写的代码:
public int max1020(int a, int b) {
if ( a>=10 && a<=20 && b>=10 && b<=20 && a>b)
return a;
if (a>=10 && a<=20 && b>=10 && b<=20 && b>a)
return b;
if (a>=10 && a<=20 && b<=10 || b>=20)
return a;
if (a<=10 || a>=20 && b>=10 && b<=20)
return b;
else return 0;
}
我相信它是正确的,但我仍然点击运行,网站说:max1020(9,21)→0但我的代码返回9.有人可以帮我查看我的代码有什么问题吗?它? :)
答案 0 :(得分:3)
public int max1020(int a, int b) {
if ( a>=10 && a<=20 && b>=10 && b<=20 && a>b)
return a;
if (a>=10 && a<=20 && b>=10 && b<=20 && b>a)
return b;
if ((a>=10 && a<=20) && (b<=10 || b>=20))
return a;
if ((a<=10 || a>=20) && (b>=10 && b<=20))
return b;
else return 0;
}
在第3行和第4行添加括号将解决问题。
我建议您更改if
语句并使用else if
。在可能的情况下,使用else if
语句而不是多个if
只是一种很好的编码习惯。
答案 1 :(得分:0)
您的代码在第三个if条件中中断,您有|| B个= 20。第3和第4个条件应更具体,如下所示:
if (a>=10 && a<=20 && (b<=10 || b>=20))
return a;
if ((a<=10 || a>=20) && b>=10 && b<=20)
return b;
添加这些括号可以解决问题。
答案 2 :(得分:0)
我更愿意将检查分配给变量以获得更“可读”的代码。但这取决于个人喜好。
public int max1020(int a, int b) {
final boolean aInRange = a>=10 && a<=20;
final boolean bInRange = b>=10 && b<=20;
if (aInRange && bInRange) {
if (a > b) {
return a;
} else if (a < b) {
return b;
} else {
return 0;
}
} else if (aInRange) {
return a;
} else if (bInRange) {
return b;
} else {
return 0;
}
}
答案 3 :(得分:0)
当然,Varun的回答是正确的。此外,我想详细说明一些评论,并展示一种解决问题的替代方法,这种方法更简单,更不可能包含错误。
在阅读问题陈述时,您可能会注意到该方法是在满足某些条件时返回值,否则返回0
。因此,您可以使用默认值0
初始化结果,如果满足条件则更改结果,然后返回结果。这会将代码减少到:
public int max1020(int a, int b) {
int result = 0;
if (a >= 10 && a <= 20) result = a;
if (b >= 10 && b <= 20 && b > result) result = b;
return result;
}
我认为不能让它变得简单得多。 (但如果你能,请评论,我爱KISS!:))
此解决方案会产生略微不同的结果,如果a
和b
都在范围内且a=b
,则会返回a
。如果发生这种情况,问题陈述并不是很清楚,正如对Varun的答案的评论所表明的那样。巧合(或不是)Codingbat没有检查这种情况。在这种情况下,网站上提出的解决方案也会返回a
。
如果您认为在0
时它应该返回a=b
,那么它很容易调整,
public int max1020(int a, int b) {
int result = 0;
if (a != b) {
if (a >= 10 && a <= 20) result = a;
if (b >= 10 && b <= 20 && b > result) result = b;
}
return result;
}
还很简单:)
解释TJCrowder关于缩进的评论:如果你将if
语句的正文放在下一行,你应该使用花括号并缩进该行。否则,它很容易被误读,或者在更改代码时出错。
// this can be error prone and harder to read,
// especially if you have multiple if statements,
// or add a statement to the body of the if statement in the future
// (shouldn't do this)
if (condition)
statement;
// Personally I think this is totally fine for a simple statement.
// But I know not everybody will agree
if (condition) statement;
// Usually, you'll see this formatting.
// Even without reading anything, the formatting makes it instantly clear
// which statements belong to the body of the if
if (condition) {
statement;
}
附注:代码中的else
语句仅属于 到最后if
。你的格式化可以通过不在它们之间加一个空行来明确,例如。
if (condition) statement;
else statement;
if (condition) {
statement;
} else {
statement;
}
在您的代码中,else
语句实际上已过时,您最后一行只能return 0;
。
Varun建议您使用else if
是正确的。从理论上讲,如果第一个if
语句的条件为真,则使用else if
会使代码跳过其他if
的测试,并且效率会更高一些。此外,它还表明只有在先前的if
语句为假时才会达到后续的if
语句。
然而,实际上,在您的代码中它并不重要,因为如果条件为true
,该方法将完成并返回一个值,并且无论如何都不会达到后续的if
语句