[ 編輯:代碼已更正并添加了輸出示例,使下面的舊評論無效。下次會更好。]
一段時間以來一直在嘗試這個 cs50 mario 更多問題,但我似乎找不到解決方案,由于某種原因,正確的金字塔似乎列印出的方式比預期的要多,我的代碼在下面,感謝我能得到的任何幫助。謝謝
#include <cs50.h>
#include <stdio.h>
int h;
int k;
int j;
int main(void)
{
while (h<=0 || h>8)
{
h = get_int ("input pyramid height:");
}
for(j=0; j<h; j )
{
for( k=0; k<=h; k )
{
if (j k<h)
printf(" ");
else
printf("#");
}
printf(" ");
for (int x=0; x<=j; x )
{
for (int y=0; y<=x; y )
printf("#");
}
printf("\n");
}
}
這就是我應該得到的高度 = 4。(抱歉之前缺少資訊)
# #
## ##
### ###
#### ####
我得到的是這個:(
# #
## ###
### ######
#### ##########
uj5u.com熱心網友回復:
在不放棄太多的情況下,“檢查問題”......
0th row: print n-0 spaces, the center '#' and LF
1st row: print n-1 spaces, 1x'#', the center again, and 1x'#' (and LF)
2nd row: print n-2 spaces, 2x'#', the center again, and 2x'#'...
3rd row: print n-3 spaces, 3x'#', the center again, and 3x'#'...
你看到這里形成了一個簡單的模式嗎?
現在垂直翻轉行編號:
8th row: print (maybe) 8 spaces, then 1 '#'
7th row: print...
6th row: pr...
太多的變數上下計數并加在一起讓人頭暈目眩……
簡化問題,各個部分應該就位。
重新開始。列印僅在一行上的“金字塔”,然后將其擴展到兩行。
編輯:
上述內容是基于我對所需輸出的錯誤理解。所需輸出的“空心核心”現在使標題“馬里奧”不那么隨機且更重要。
既然您已經發布了一個“更整潔”的代碼版本,并且(經過一些修飾)期望/實際輸出,那么(在 SO 上)可以幫助您解決遇到的困難......
第二個內for()
回圈應該是好的第一個回圈的鏡像for()
。倒數吧。
for( k=0; k<=h; k ) // ascending left
{
if (j k<h)
printf(" ");
else
printf("#");
}
printf(" ");
for( k=h; k>0; k--) // descending right side
{
if (j k<h)
printf(" ");
else
printf("#");
}
printf("\n");
這會輸出不必要的空格,但代碼很容易讓讀者“顯而易見”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/507340.html