从 Java 递归开始(对大多数人来说可能很简单?) [英] Starting with Java recursion (probably an easy ? for most)

查看:31
本文介绍了从 Java 递归开始(对大多数人来说可能很简单?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在解决以下问题:

Hi I am working on the following problem:

编写一个递归函数,计算数组的负数之和.从 main 方法传入数组 {15 , -7 , -19 , 8 , 5 , -6 , -1} .

Write a recursive function that calculates the sum of the negative numbers of the array. Pass in the array {15 , -7 , -19 , 8 , 5 , -6 , -1} from the main method.

递归函数应该返回结果 -33 .在 main 方法中打印出这个值.这个程序应该命名为 Negsum.java

The recursive function should return the result -33 . Print out this value in the main method. This program should be named Negsum.java

这是我目前所拥有的,但它输出的是 6.0,而不是 -33.

This is what I have so far, but it prints out 6.0, not -33.

public class Negsum {

    static double findSum(double array[], int n){
        double sum=0;
        if(array[n]>0) 
            return 1;
        else
            return array[n-1] + findSum(array, n-1);
    }

    public static void main(String args[]){
        double array[]={15, -7, -19, 8, 5, -6, -1};
        System.out.println(findSum(array, 5));
    }
}

推荐答案

您的代码有几个问题.我怀疑你根本不明白你想要做什么.这不能在这里解决——你需要花更多的时间学习,直到你真正明白.

There are several things wrong with your code. I suspect that you simply don't understand what you're trying to do. That can't be fixed here -- you need to spend some more time studying until you really get it.

但我注意到以下几点可能会为您指明正确的方向:

But here's a few things I noticed that may point you in the right direction:

  • n 参数的目的是什么?它应该以某种方式与数组的长度有关吗?也许您可以使用方法重载将其传递给您的递归函数,而不是传递给递归入口点?

  • What is the purpose of the n argument? Should it be somehow related to the length of the array? Perhaps you could use method overloading to pass it to your recursive function but not to the recursion entry point?

为什么你的代码中有一个return 1;?1 应该代表什么?

Why do you have a return 1; in your code? What is the 1 supposed to represent?

您已经声明了一个变量 sum,但它从未被使用过.您打算在哪里使用 sum 变量?

You have declared a variable sum, but it is never used. Where were you intending to use the sum variable?

也许通过思考这些问题,您将能够找到可行的解决方案.

Perhaps by thinking about these questions you will be able to find a working solution.

这篇关于从 Java 递归开始(对大多数人来说可能很简单?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆