繁体   English   中英

在 Dr.Java 中递增

[英]Incrementing in Dr.Java

编写一个递归方法“countToBy”,它接受两个整数参数 n 和 m,并产生指示如何以 m 为增量计数到 n 的输出。

例如,要从 1 数到 10,您可以说: countToBy(10, 1); 这应该产生以下输出:1, 2, 3, 4, 5, 6, 7, 8, 9, 10

增量不一定是 1。例如,下面的调用表明我们要以 4 的增量计数到 25: countToBy(25, 4); 产生这个输出: 1, 5, 9, 13, 17, 21, 25


我的代码是:

import java.util.*;
import java.io.*;

public class CountBy {

  public static void main(String[] args) { 
    countToBy(34, 5);
    System.out.println(); 
    countToBy(3, 6);
    System.out.println(); 
    countToBy(17, 3);
    System.out.println(); 
  }

  // *** Your printSorted method goes here ***
  public static void countToBy(int max, int var){
    if (max < var)
      System.out.print("Error, max value too low or skip value too high.");
      else{
        for (int x = var-1; x<=max; x = x + var){
          System.out.print(x + ", ");
}
    }
}
}

这有效,但我觉得我错过了一些东西......任何帮助将不胜感激。

只是为了让您了解如何编写这种递归方法:

public static void method(int x, int y){
        if(x<y) return;
        method(x-1, y);
        System.out.print(x + " ");      
}

此方法打印从yx的数字序列。 所以对于method(20,10); 它将打印出: 10 11 12 13 14 15 16 17 18 19 20

public class test {
void counttoby(int n,int m,int aff){
    if(aff==n) System.out.println(n);
    else{
        if(n<aff) System.out.println("error");
        else{
        counttoby(n,m,aff+m);
        System.out.println(aff);
        }
    }
}
public static void main(String[] args) {
    test t= new test();
    t.counttoby(10, 1,1);

}

}

试试这个代码好吗

暂无
暂无

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

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