[問題] 自寫求幾位數的程式怪怪的..幫忙找錯誤~

看板C_and_CPP (C/C++)作者 (不要問 很恐怖)時間15年前 (2011/05/10 23:51), 編輯推噓3(304)
留言7則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Dev-C++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) <stdio.h> <stdlib.h> <math.h> 問題(Question): 輸入一整數,求其幾位數 餵入的資料(Input): #include <stdio.h> #include <stdlib.h> #include <math.h> int digit(int); int main(void) { int n; printf("請輸入n值來計算n為幾位數\n"); scanf("%d",&n); printf("%d位數\n",digit(n)); system("pause"); return 0; } int digit(int n) { float a; a=log(n); if(a==(int)a) return a; else return (int)a+1; } 預期的正確結果(Expected Output): 123→3位數 錯誤結果(Wrong Output): 123→5位數 程式碼(Code):(請善用置底文網頁, 記得排版) #include <stdio.h> #include <stdlib.h> #include <math.h> int digit(int); int main(void) { int n; printf("請輸入n值來計算n為幾位數\n"); scanf("%d",&n); printf("%d位數\n",digit(n)); system("pause"); return 0; } int digit(int n) { float a; a=log(n); if(a==(int)a) return a; else return (int)a+1; } 補充說明(Supplement): 新手發問,格式若有誤,請見諒~~^^ 謝謝~~ -- @Windows Live Examiner 目前的狀態為「逃避現實」,您可以前往參加考試,但教授將知道您沒有讀書。 ▁▁▁▁▁▁▁▁ ▁▁▁▁▁ ▁▁▁▁▁▁▁▁ 參加考試(T) 裝死(P) 申請退選(L) ψegoweaver▇▇▇▇▇▇▇▇ ▇▇▇▇▇ ▇▇▇▇▇▇▇▇ ψflylitlig -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.125.203.35

05/10 23:58, , 1F
這個log()是以e為底 改用log10()吧
05/10 23:58, 1F

05/11 00:16, , 2F
喔..謝謝~ 我之前都不知耶~~感恩
05/11 00:16, 2F

05/11 00:45, , 3F
用 sprintf 轉成字串再算字元個數就好了
05/11 00:45, 3F

05/11 00:45, , 4F
printf 系列函數的底層函數,那個 "%d" "%f" 的判斷程式碼
05/11 00:45, 4F

05/11 00:46, , 5F
大概是 C 語言裡面最複雜的
05/11 00:46, 5F

05/11 16:46, , 6F
樓上, http://ppt.cc/XAa1 直接取sprintf() 回傳值即可XD
05/11 16:46, 6F

05/11 16:50, , 7F
沒注意到 謝謝
05/11 16:50, 7F
文章代碼(AID): #1DoLyOPZ (C_and_CPP)
文章代碼(AID): #1DoLyOPZ (C_and_CPP)