如何在Java递归程序中打印值? [英] How Do I Print the values in a recursive Program in Java?

查看:49
本文介绍了如何在Java递归程序中打印值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用递归程序打印出一个从一个值开始,到最大值,然后再回到原始值的序列.该程序不能使用静态或全局变量,也不能使用数组.

I am trying to use a recursive program to print out a sequence that starts at one value, goes to a max, then back down to the original value. The program can't use static or global variables, or use an array.

例如: f(5,10)打印 5,6,7,8,9,10,9,8,7,6,5

Ex: f(5,10) prints 5,6,7,8,9,10,9,8,7,6,5

我认为我有这个概念,至少我认为是这样,但是我不知道如何从递归方法中打印变量以打印序列.
这是我的程序:

I think I have the concept down, at least I think I do, but I can't figure out how to print the variable from the recursive method to print the sequence.
Here is my program:

 public class recursive {

     public static int f(int a, int b) {
         System.out.print(a);   
         if (a == b) return a;
         else return a + f(a + 1, b) + a;

     public static void main(String[] args) {
         f(2, 5);
     }

 }

是否需要更改程序才能打印?我相当确定我的概念是正确的,只是无法打印出来.请帮忙!!!!

Do I need to Change the program to be able to print? I am fairly certain my concept is correct, I just can't print it. Please help!!!!

推荐答案

如果必须在递归函数中打印,则只需打印而不返回即可.

If you must print inside the recursive function, just print instead of returning..

public static void f(int a, int b) {
    if (a == b) {
        System.out.print(a);
    }
    else {
        System.out.print(a + ",");
        f(a+1,b);
        System.out.print("," + a);
    }
}

这篇关于如何在Java递归程序中打印值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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