这是问题 1。编写一个递归解决方案,将一个整数除以另一个整数并给出答案。例如 35/7 = 5。
public class Division
{
public static void main(String[] args)
{
int a = 10;
int b = 5;
int answer = divide(a,b);
return;
}
private static int divide(int a, int b)
{
int answer = a/b;
return divide(a,b);
}
}
最佳答案
您收到堆栈溢出错误,因为您的递归函数 divide
没有终止条件并且始终会调用自身。一个好的递归函数有一个终止条件来中断它的自调用。
我认为这个问题与从结果中减去 b
直到达到负值有关...例如 35/6,
35
- 6 = 29
- 6 = 23
- 6 = 17
- 6 = 11
- 6 = 5 - 6 = -1
在结果变为负数之前,您必须减去 6 五 次,所以答案是 5。
类似...
private static int divide(int a, int b) {
if (a - b < 0) { // or simply (a < b)
return 0;
}
return divide(a - b, b) + 1;
// +1 because I needed to count the number of times
// I've subtracted b from the running value.
}
关于java - 这个递归示例是如何工作的?我不断收到堆栈溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43420377/