[爆卦]puts printf差別是什麼?優點缺點精華區懶人包

為什麼這篇puts printf差別鄉民發文收入到精華區:因為在puts printf差別這個討論話題中,有許多相關的文章在討論,這篇最有參考價值!作者shadowjohn (會吐槽的最強)看板C_and_CPP標題Re: [問題] 金字塔製作時間...



#include <iostream>
#include <string>
using namespace std;
int main()
{
int k=0;
cout << "要查幾層金字塔:";
cin >> k;
for(int i = 0 ; i < k ; i++ )
cout << string(k-i-1,' ') << string((i+1)*2-1,'*') << endl;
return 0;
}

[root@localhost c]# c++ gold_3wa.c -o gold_3wa && ./gold_3wa
要查幾層金字塔:5
*
***
*****
*******
*********
[root@localhost c]#

附上跑一萬個星號的時間

[root@localhost c]# time echo 10000|./gold_3wa > /dev/null

real 0m0.188s
user 0m0.116s
sys 0m0.076s
[root@localhost c]#
[root@localhost c]# time echo 10000|./gold_3wa > /dev/null

real 0m0.188s
user 0m0.116s
sys 0m0.076s
[root@localhost c]#
[root@localhost c]# time echo 10000|./gold_3wa > /dev/null

real 0m0.188s
user 0m0.116s
sys 0m0.076s
[root@localhost c]#

另外寫一個純 C 的寫法是這樣


#include <stdio.h>
int main(){
int k;
printf("要幾層金字塔:");
scanf("%d",&k);
for( int i = 0 ; i < k ; i++ ) {
printf("%*s", k - i - 1 ,"");
for( int j = i * 2 ; j >= 0 ; j-- ){
putchar('*');
}
puts("");
}
return 0;
}

//主要差別在於利用 printf 可以印足所需的空白
//下一個 j 迴圈 只需跑同一行 * 所需要數量,並且下數印出

[root@localhost c]# cc -std=c99 gold_3wa_c.c -o gold_3wa_c

[root@localhost c]# ./gold_3wa_c
要幾層金字塔:5
*
***
*****
*******
*********
[root@localhost c]#


附上跑 10,000 個星號 的時間

[root@localhost c]# time echo 10000|./gold_3wa_c > /dev/null

real 0m5.906s
user 0m5.818s
sys 0m0.089s
[root@localhost c]# time echo 10000|./gold_3wa_c > /dev/null

real 0m5.815s
user 0m5.734s
sys 0m0.079s
[root@localhost c]# time echo 10000|./gold_3wa_c > /dev/null

real 0m5.713s
user 0m5.642s
sys 0m0.072s
[root@localhost c]#

--
3WA訓練家的工作室

宗旨:諸葛單中,謝謝

個人佈弱格 網址:http://3wa.tw

--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 123.240.117.97
※ 編輯: shadowjohn 來自: 123.240.117.97 (08/04 03:12)
※ 編輯: shadowjohn 來自: 123.240.117.97 (08/04 06:45)
※ 編輯: shadowjohn 來自: 123.240.117.97 (08/04 15:33)
firejox:http://codepad.org/qipScigL 08/04 20:59
firejox:real 0m0.221s user 0m0.152s sys 0m0.008s 08/04 21:00
shadowjohn:GG 08/04 22:49

你可能也想看看

搜尋相關網站