gpt4 book ai didi

java - 使用递归计算可被 3 整除的总和

转载 作者:行者123 更新时间:2023-12-01 13:52:26 25 4
gpt4 key购买 nike

我需要帮助弄清楚如何返回从键盘输入的二维数组中可被三整除的所有数字的总和。我的计算总和方法可以正确返回一个测试用例,但是它不能正确计算给定的每种情况。任何建议都会非常有帮助。我将加载我的代码,包括 while 循环,以便更容易找到我计算错误的地方。

try
{
InputStreamReader stream = new InputStreamReader (System.in);
BufferedReader scan = new BufferedReader(stream);

inputParser = Integer.parseInt(input);

int i = 0;
while(inputParser != 0)
{
input = scan.readLine();
inputParser = Integer.parseInt(input);
if(inputParser == 0)
{
inputParser = 0;
}
else
{
numbers1[i] = inputParser;
i++;
}
}

sum = computeSumDivisibleBy3(numbers1,0,numbers1.length-1);
System.out.println("The sum of the numbers divisible by 3 is " + sum);

}
catch(NumberFormatException exception)
{
System.out.println("Please enter integers only");
}

这里是计算总和能被3整除的方法

//我在下面实现了你的方法,而不是这个原始方法,并且它返回正确

public static int computeSumDivisibleBy3(int[] numbers, int startIndex, int endIndex){
if (startIndex == endIndex)
return numbers[endIndex];
else{
int sum1 = computeSumDivisibleBy3(numbers, startIndex, endIndex-1);
if (numbers[endIndex] % 3 == 0)
return sum1 + numbers[endIndex];

else

return sum1;

}

}
//newly implemented code
public static int computeSumDivisibleBy3(int[] numbers, int startIndex, int endIndex){
if (startIndex == numbers.length-1)
return numbers[startIndex] % 3 == 0 ? numbers[startIndex] : 0;
else{

return (numbers[startIndex] % 3 == 0 ? numbers[startIndex] : 0) + computeSumDivisibleBy3( numbers, ++startIndex, endIndex );

}

}

最佳答案

// is startIndex really needed? you only ever use it unnecessarily, so, no.
public static int computeSumDivisibleBy3(int[] numbers, int startIndex, int endIndex){
// End condition, good, but the return value doesn't make any sense
// You always return the last one in the array, even it's not divisible by 3
//if (startIndex == endIndex)
// return numbers[endIndex];

// How about this instead (taking the removal of startIndex into consideration)
if( index == numbers.length - 1) {
return (numbers[index] % 3 == 0 ? numbers[index] : 0);
}

// now, on to regular operations
// all that's needed is to return the current element, or zero, plus the recursive result
return (numbers[index] % 3 == 0 ? numbers[index] : 0) + computeSumDivisibleBy3( numbers, ++index );

// or, if you'd prefer an if statement
int cur = 0;
if( current element % 3 is 0 ) {
cur = current element
}
return cur + recurse( numbers, ++index );

//else{
// int sum1 = computeSumDivisibleBy3(numbers, startIndex, endIndex-1);
// if (numbers[endIndex] % 3 == 0)
// return sum1 + numbers[endIndex];

// else

//return sum1;

}

}

关于java - 使用递归计算可被 3 整除的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19868604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com