我正在嘗試撰寫一種方法,該方法將基于遞回的高度引數列印具有高度的金字塔。
示例輸出為: printPyramid(5);
*
**
***
****
*****
****
***
**
*
當它需要開始將星數減回到 1 并且我無法弄清楚我的邏輯在哪里關閉時,它會向我發送堆疊溢位錯誤。它成功地向上遞增,檢查迭代是否大于高度,然后開始遞減,并在迭代為零時停止遞回——但我仍然遇到錯誤。
public static void printPyramid(int height){
if(height == 0) {
return;
} else {
printPyramidRow(1, height);
}
}
public static void printPyramidRow(int it, int height) {
if(it <= 0) {
return;
} else {
printRow(it);
if (it < height) {
printPyramidRow(it 1, height);
} else {
printPyramidRow(it - 1, height);
}
}
}
public static void printRow(int numOfStars) {
for(int i = 1; i < numOfStars 1; i ) {
if(i == numOfStars) {
System.out.println("*");
} else {
System.out.print("*");
}
}
}
uj5u.com熱心網友回復:
if (iteration < height) {
printTriangle(iteration 1, height);
} else {
printTriangle(iteration - 1, height);
}
這部分代碼是有問題的。您最初擁有的數量iteration少于,height然后您增加它。達到最大值后,您遞減一次,但在下一次遞回中,您將再次遞增。你被困在最大值附近的增量和減量中。
你可能想改變你的 if 條件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/487716.html
上一篇:Webpack,禁用匯出SCSS/CSS中參考的資產
下一篇:具有遞回的Python算術函式
