将迭代代码转换为递归代码

huangapple go评论89阅读模式
英文:

Converting iterative code to recursive code

问题

我需要一些关于那个函数的帮助。我将在其他函数中使用“val”,但是当我尝试在递归函数中返回这个值时,它总是返回0。我需要将这个循环放入递归函数中。
对我的英语表示抱歉。非常感谢。

  1. int val = 0;
  2. for (int i = 0; i < arreglo.length; i++) {
  3. if (arreglo[i] % 2 != 0) {
  4. val++;
  5. }
  6. }
英文:

I need some help with that function. I gonna use "val" in other functions but when I try to return the value in a recursive function just return 0. I need to make this loop in a recursive function
Sorry for my English. Thanks a lot

  1. int val = 0;
  2. for (int i = 0; i &lt; arreglo.length; i++) {
  3. if (arreglo[i] % 2 != 0) {
  4. val++;
  5. }
  6. }

答案1

得分: 1

这里是一个简单的示例,演示如何实现这个过程:

对于递归的基本情况,您需要提供起始索引和初始值,因此将 index 参数设为 0,val 参数设为 0:

  1. public class Recursive{
  2. public static int recursive(int[] arreglo, int index, int val) {
  3. if (index == arreglo.length ) {
  4. return val;
  5. } else {
  6. if (arreglo[index] % 2 == 0) {
  7. val++; // 增加值 - 偶数
  8. }
  9. return recursive(arreglo, index+1, val);
  10. }
  11. }
  12. public static void main(String []args){
  13. int[] r = {1, 2, 3, 4, 5, 6, 7, 8};
  14. int result = recursive(r, 0, 0);
  15. System.out.println(result); // 输出 4
  16. }
  17. }
英文:

Here's a simple example how this can be done:

For the base case of recursion you have to provide starting index and initial value, so pass 0 for index parameter and 0 for val parameter:

  1. public class Recursive{
  2. public static int recursive(int[] arreglo, int index, int val) {
  3. if (index == arreglo.length ) {
  4. return val;
  5. } else {
  6. if (arreglo[index] % 2 == 0) {
  7. val++; // increment value - even number
  8. }
  9. return recursive(arreglo, index+1, val);
  10. }
  11. }
  12. public static void main(String []args){
  13. int[] r = {1, 2, 3, 4, 5, 6, 7, 8};
  14. int result = recursive(r, 0, 0);
  15. System.out.println(result); // Outputs 4
  16. }
  17. }

huangapple
  • 本文由 发表于 2020年10月25日 10:57:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/64519897.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定