久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

遞歸地對數組中的整數求和

recursively sum the integers in an array(遞歸地對數組中的整數求和)
本文介紹了遞歸地對數組中的整數求和的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我有一個程序,我正在嘗試為類創建一個使用遞歸返回數組中所有整數之和的程序.到目前為止,這是我的程序:

I have a program that I'm trying to make for class that returns the sum of all the integers in an array using recursion. Here is my program thus far:

public class SumOfArray {

private int[] a;
private int n;
private int result;

    public int sumOfArray(int[] a) {

      this.a = a;
      n = a.length;

      if (n == 0)  // base case
      result = 0;
      else
          result = a[n] + sumOfArray(a[n-1]);

      return result;

   } // End SumOfArray method

} // End SumOfArray Class 

但是我相信我遇到了三個相關的錯誤,但我無法弄清楚為什么它會找到一種 null:

But I'm getting three error which are all related, I believe, but I can't figure out why it is finding a type of null:

SumOfArray.java:25: sumOfArray(int[]) in SumOfArray cannot be applied to (int)
    result = a[n] + sumOfArray(a[n-1]);
                    ^
SumOfArray.java:25: operator + cannot be applied to int,sumOfArray
    result = a[n] + sumOfArray(a[n-1]);
              ^
SumOfArray.java:25: incompatible types
found   : <nulltype>
required: int
    result = a[n] + sumOfArray(a[n-1]);
                  ^
3 errors

推薦答案

解決方案比看起來簡單,試試這個(假設一個非零長度的數組):

The solution is simpler than it looks, try this (assuming an array with non-zero length):

public int sumOfArray(int[] a, int n) {
    if (n == 0)
        return a[n];
    else
        return a[n] + sumOfArray(a, n-1);
}

這樣稱呼它:

int[] a = { 1, 2, 3, 4, 5 };
int sum = sumOfArray(a, a.length-1);

這篇關于遞歸地對數組中的整數求和的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to wrap text around components in a JTextPane?(如何在 JTextPane 中的組件周圍環繞文本?)
MyBatis, how to get the auto generated key of an insert? [MySql](MyBatis,如何獲取插入的自動生成密鑰?[MySql])
Inserting to Oracle Nested Table in Java(在 Java 中插入 Oracle 嵌套表)
Java: How to insert CLOB into oracle database(Java:如何將 CLOB 插入 oracle 數據庫)
Why does Spring-data-jdbc not save my Car object?(為什么 Spring-data-jdbc 不保存我的 Car 對象?)
Use threading to process file chunk by chunk(使用線程逐塊處理文件)
主站蜘蛛池模板: 91视频麻豆| 国产高清美女一级a毛片久久w | 国产精品乱码一区二三区小蝌蚪 | 国产精品乱码一区二区三区 | 色综合视频在线 | 国产探花在线精品一区二区 | 91成人在线 | 亚洲精品亚洲人成人网 | 97色在线视频 | 欧美成人a∨高清免费观看 欧美日韩中 | 99久久久久久99国产精品免 | 国产亚洲成av人片在线观看桃 | 一区二区三区精品 | 欧美成视频| 国产一区在线免费观看视频 | 色伊人网| 国产一二区视频 | 成人网在线观看 | 亚洲精品一区二区二区 | 亚洲一区二区国产 | 亚洲精品小视频在线观看 | 激情 一区 | 成人精品视频 | 男女免费视频网站 | 久久精品青青大伊人av | 久久国产精品亚洲 | 欧美伦理一区 | 羞羞免费网站 | 天天影视网天天综合色在线播放 | 欧美电影在线 | 日韩欧美国产精品 | 精品在线看 | 美人の美乳で授乳プレイ | 七七婷婷婷婷精品国产 | 久久久国产精品 | 成人在线视频免费看 | 精品国产免费人成在线观看 | 亚洲视频在线看 | 成人深夜福利 | 国产精品久久久久久久午夜片 | chinese中国真实乱对白 |