英文:
Java function is not returning expected value
问题
程序中的一个错误。我正在为我的Java作业编写此程序。
目标: 该程序应该接受两个参数,并找到这些参数之间的所有奇数,然后返回所有这些数字的总和。
错误: 当参数为负数或起始数字大于结束数字时,应返回-1。但是我的程序返回0。
也许我的程序没有在循环内更新总和值。但是即使如此,根据返回条件,我的函数应该返回-1,而不是总和。
public class SumOddRange{
public static void main(String[] args){
System.out.println(sumOdd(10,5));
}
public static boolean isOdd(int number){
return (number < 0) || (number % 2 == 0) ? false : true;
}
public static int sumOdd(int start, int end){
int sum = 0;
for(int i = start; i <= end; i++){
if(isOdd(i)){
sum += i;
}
}
return (start <= 0) && (start > end) ? -1 : sum;
}
}
英文:
A bug in a program I'm writing as an assignment for my java.
Objective: program should take two parameters and find all the odd numbers between those parameters. Then it should return the sum of all those numbers.
Bug: When the parameters are negative or starting number is greater than the ending number, it should return -1. But my program is returning 0.
Maybe my program isn't updating the sum value inside the loop. But even so, as per return condition, my function should return -1, not the sum.
public class SumOddRange{
public static void main(String[] args){
System.out.println(sumOdd(10,5));
}
public static boolean isOdd(int number){
return (number<0)||(number%2==0)?false:true;
}
public static int sumOdd(int start, int end){
int sum = 0;
for(int i=start; i<=end; i++){
if(isOdd(i)){
sum+=i;
}
}
return (start<=0)&&(start>end)? -1: sum;
}
}
答案1
得分: 3
把输入检查放在方法的第一部分,并将 &&
改为 ||
,因为你希望在第一个检查失败时返回,或者在第二个检查失败时返回,不仅仅是在两者都失败时返回。isOdd
可以内联:
public static int sumOdd(int start, int end){
if (start <= 0 || start > end)
return -1;
int sum = 0;
for (int i = start; i <= end; i++) {
if (i % 2 != 0) { // 或者 if (i % 2 == 1) {
sum += i;
}
}
return sum;
}
英文:
Put the input check as the first thing in your method and change the &&
to an ||
since you want to return if the first check fails or the second check fails, not only if both fail. And the isOdd
can be inlined:
public static int sumOdd(int start, int end){
if (start <= 0 || start > end)
return -1;
int sum = 0;
for (int i = start; i <= end; i++) {
if (i % 2 != 0) { // or if (i % 2 == 1) {
sum += i;
}
}
return sum;
}
答案2
得分: 1
在您的代码行中存在逻辑错误:return (start<=0)&&(start>end)? -1: sum;
如果 start
小于 0 或者 start
大于 end
,您需要返回 -1,因此应该使用 "||"(逻辑或) 而不是 "&&"(逻辑与):
return (start<=0)||(start>end)? -1: sum;
请参考 @luk2302 的回答,以获得更好的解决方案。
英文:
There is a logic error in your line return (start<=0)&&(start>end)? -1: sum;
You have to return -1 if start is <0 or start > end, so use "||" (logical Or) instead of "&&" (logical and):
return (start<=0)||(start>end)? -1: sum;
Please go through @luk2302's answer for a better solution.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论