-4

所以问题是:

用户必须指定 2 个编号的M(起点)和N(终点)

程序必须在以下条件下检查 M 和 N 之间的所有数字:

  • 如果能被 3 整除,则打印“被 3 整除”
  • 如果能被 5 整除,则打印“被 5 整除”
  • 如果能被 3 和 5 整除,则打印“被两者整除”


只有在允许循环检查条件的情况下,Java 中的解决方案才会非常感激

4

2 回答 2

0

如果你想要递归

 void func(int M,int N)
{ 
if (M>N)
return;
 else
  {
   i=M;
    if(i%5==0 && i%3==0){

       system.out.println(i + "is divisible by both 3 and 5");

    }else if(i%5==0){

       system.out.println(i + "is divisible by  5");

    }else if(i%3==0){

       system.out.println(i + "is divisible by  3");

    }
    func(M++,N);
 }

}
于 2013-04-10T07:14:47.623 回答
0

这是我的尝试,过程称为Recursion.

public class Main {

    private static int M, N;

    public static void main(String[] args) {
        M = 0; // min value
        N = 10; // max value
        noLoop(M); // begin the method
    }

    private static void noLoop(int currentNumber) {
        String resultMessage;

        if (currentNumber % 3 == 0) {
            resultMessage = currentNumber + " is divisible by 3.";
        } else {
            resultMessage = currentNumber + " is NOT divisible by 3.";
        }

        if (currentNumber % 5 == 0) {
            resultMessage = currentNumber + " is divisible by 5.";
        } else {
            resultMessage = currentNumber + " is NOT divisible by 5.";
        }

        if (currentNumber % 3 == 0 && currentNumber % 5 == 0) {
            resultMessage = currentNumber + " is divisible by BOTH 3 and 5.";
        }

        System.out.println(resultMessage);
        M++; // min value + 1
        if (M <= N) { // if min value == max value, STOP!
            noLoop(M);
        }
    }
}
于 2013-04-10T07:18:19.053 回答