繁体   English   中英

递归方法,将计算至少n个整数的数组中前n个整数的和。 以第n个整数开头

[英]Recursive method that will compute the sum of the first n integers in an array of at least n integers. Begin with nth integer

到目前为止,这是我的代码,但是当我运行它并为n输入一个值时,程序以“数字和为:”结尾,仅此而已。 无论我输入什么值都不会改变,您能帮助我弄清楚我做错了什么吗?

import java.util.Scanner;
class addNum
{
    //A method for Adding
    public static int addNum (int arr[], int n)
    {
      int x = 0;
      if (n > arr.length)
      {
          return 0;
      }
      else if (n == 1)
      {
          return 1;
      }
      else 
      {
         x = arr[n-1] + addNum(arr, n);
         return n;
      }
     }

    public static void main(String args[])
    {
        int n = 0;
        int arr[] = {1,2,3,4,5,6,7};
        System.out.println("Input your number and press enter: ");
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        System.out.print("Sum of numbers is:");
        addNum(arr, n);
        System.out.println();
        }
    } 

尝试将其更改为

    System.out.println(addNum(arr, n));

所以实际上返回并打印了一些东西

而且有一个错误

x = arr[n-1] + addNum(arr, n);
return x;  // not n
addNum(arr, n);

这只是一个函数调用addNum(param1,param2)。

它只会是返回值,而不是输出值。 因此,您必须打印出该值才能看到它。

System.out.println(addNum(arr, n));

正如Siren P.提到的那样

尝试这个:

public static int addNum (int arr[], int n)
        {
          int x = 0;
          if (n > arr.length)
          {
              return 0;
          }
          else if (n == 1)
          {
              //When n == 1, you want to return the first element of your array and not 1
              return arr[0];
          }
          else 
          {
             //As you go deeper into recursion, you break your problem into a smaller problem.
             //Therefore, when calling addNum again, you pass n-1 and not n, as now you want to add remaining n-1 numbers 
             x = arr[n-1] + addNum(arr, n-1);
             // you want to return your sum x and not n
             return x;
          }
         }

        public static void main(String args[])
        {
            int n = 0;
            int arr[] = {1,2,3,4,5,6,7};
            System.out.println("Input your number and press enter: ");
            Scanner in = new Scanner(System.in);
            n = in.nextInt();
            System.out.print("Sum of numbers is:");
            //Your addNum method returns an int, so you want to save it in a variable and then print it 
            int x = addNum(arr, n);
            System.out.println(x);
            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM