[問題] 求integer長度

看板C_and_CPP (C/C++)作者 (Mx. YAN)時間12年前 (2013/12/14 19:21), 編輯推噓1(104)
留言5則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Windows 問題(Question): 求變數a的長度 餵入的資料(Input): a = 9 預期的正確結果(Expected Output): 1 錯誤結果(Wrong Output): 309 程式碼(Code):(請善用置底文網頁, 記得排版) int main() { int a = 9; int count = 1; while(a / pow(10.0, count) != 0) { count++; } cout << count << endl; system("PAUSE"); return 0; } 補充說明(Supplement): 有把cout << count; 放入while中,結果是從0加到309 是我的想法有錯嗎? 想法: 變數a,9 / 10的一次方,結果為0那他連while都不會進入 直接cout 印出1 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 123.192.24.211

12/14 19:34, , 1F
pow 的回傳值是 double ,會變 a/10.0 ,變 0.9
12/14 19:34, 1F
改成static_cast<int>a / pow(10.0, count)就可以了 學到了 int / double = double ※ 編輯: nature23306 來自: 123.192.24.211 (12/14 19:42)

12/14 23:26, , 2F
12/14 23:26, 2F

12/15 03:12, , 3F
log要看實作 不見得會比較快 不過在數學上是比較理想啦
12/15 03:12, 3F

12/16 18:45, , 4F
這樣子做就可以了 while((int)(a / pow(text, count) )!= 0)
12/16 18:45, 4F

12/16 18:48, , 5F
這樣就可以印出1 符合你想要的需求了
12/16 18:48, 5F
文章代碼(AID): #1Ih3zDtP (C_and_CPP)
文章代碼(AID): #1Ih3zDtP (C_and_CPP)