頁:
[1]
c程式三角形只能用for迴圈嗎?
http://pastie.org/10958869這個是用for迴圈寫出來的菱形(上下各1個三角形) 請問除了這種方法還有其他能寫出三角形的形狀嗎?
<div></div> 只用 print f ...
print f(" * \n");
print f(" *** \n");
print f(" ***** \n");
hst326 發表於 2016-11-11 10:20 PM static/image/common/back.gif
只用 print f ...
print f(" * \n");
哈哈哈 無敵的 print f();
本帖最後由 CoNsTaRwU 於 2016-11-20 08:54 PM 編輯
所有的迴圈都可以規約成遞迴
在 λcalculus 裡是用 Y-combinator 和 Z-combinator 來做到 generic recurrsion 的,可以參考
簡單一點的說法,要是一個函數的參數和回傳值具有全序關係(序理論中的),而且總是其中一方大於/小於另一方,則這個函數可以被用作遞迴
或者是你能夠找到這個函數的 fixed-point,這個函數也同樣能夠用作遞迴
因此可以不使用迴圈,只用遞迴也能夠做到一樣的計算結果
例如你的例子:
printTri : Nat → Nat →
printTri x x = (repeat x "*") ++ "\n"
printTri x y = levelx ++ printTri x (y+1) where
levelx = spaces ++ stars ++ "\n"
spaces = repeat (x-y) " "
stars = repeat (1+(y-1)*2) "*"
...<div class='locked'><em>瀏覽完整內容,請先 <a href='member.php?mod=register'>註冊</a> 或 <a href='javascript:;' onclick="lsSubmit()">登入會員</a></em></div> 也可以寫個副程式,通過呼叫來達成!!<br><br><br><br><br><div></div> 用 for 迴圈可以讓程式比較活一點
可以很彈性的改變三角形的大小
比用 print 好,但是比較難寫 while 跟do while也可以達的到阿 本帖最後由 yynnyyee 於 2022-1-5 12:54 AM 編輯
#include <stdio.h>
int main()
{
char buffer = " _ ";
int i;
for (i=0; i<5; i++)
{
buffer = buffer = '*';
用 printf 印出 buffer 字串
}
while (--i)
{
buffer = buffer = ' ';
用 printf 印出 buffer 字串
}
return 0;
}
頁:
[1]