Re: [問題] 面試考題

看板C_and_CPP作者 (風月)時間15年前 (2010/08/10 08:46), 編輯推噓1(103)
留言4則, 2人參與, 最新討論串3/3 (看更多)
Environment : winXP sp2,Code:Block 10.5,gcc 4.4.1 sample code ============================================================= #include <stdio.h> #include <stdlib.h> int main() { char src[12] = {0}; int temp = 0; int cnt = 0; int i = 0; scanf("%s",src); for (;;){ cnt = strlen(src); if (cnt < 2){ break; } temp = 0; for (i=0;i<cnt;i++){ temp += src[i] - '0'; //重點 } sprintf(src,"%d",temp); } printf("result = %s",src); return 0; } input : 454 output : 4 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.62.64.95

08/10 18:10, , 1F
謝謝 我寫出來了
08/10 18:10, 1F

08/11 07:23, , 2F
其實sprintf()的回傳值就是src的長度, 可以少做一次strlen
08/11 07:23, 2F

08/11 07:24, , 3F
順帶一提, printf()回傳的東西是"印出來的資料"的長度
08/11 07:24, 3F

08/11 07:25, , 4F
然後temp += (src[i] - '0'); //加個括號是個好做法
08/11 07:25, 4F
文章代碼(AID): #1COH7_NW (C_and_CPP)
討論串 (同標題文章)
完整討論串 (本文為第 3 之 3 篇):
問題
1
4
問題
0
4
問題
2
21
文章代碼(AID): #1COH7_NW (C_and_CPP)