[英]Recursive function to print all numbers in ascending order up to the given entered number
我已經為正整數工作了一切,但無法弄清楚如何使用負整數。 它從最大值到最小值打印它。 我希望它與正整數相同,從最小值到最大值。
import java.util.Scanner;
public class Ascending {
public static void ascendingorder(int n){
if (n > 0) {
ascendingorder(n - 1);
System.out.print(n + " ");
}
else if(n < 0){
ascendingorder(n + 1);
System.out.print(n + " ");
}
}
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter an Integer Number: ");
int n = in.nextInt();
ascendingorder(n);
System.out.println();
}
}
如果我理解你的問題,答案可能只是反轉else if
語句中的行:
ascendingorder(n + 1);
System.out.print(n + " ");
所以它會是
System.out.print(n + " ");
ascendingorder(n + 1);
同樣的觀察發現你只需要在為負整數調用遞歸之前先寫打印語句
在這種情況下,您 function 加 1 直到 n 變為 0。然后它打印從 0 到 n 的值。 為了防止它,你應該先打印 n 然后你應該增加它的價值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.