[問題] C++ 做平方根
開發平台(Platform): (Ex: Win10, Linux, ...)
WIN10
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
VS2015
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
各位前輩好
小弟在做平方根時(只需要取整數部分ex:輸入8,得到2)
發現數字變大後會出現錯誤的輸出
不知道是不是程式有欠缺考慮的部分
餵入的資料(Input):
2147395600
預期的正確結果(Expected Output):
46340
錯誤結果(Wrong Output):
289398
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
int mySqrt(int x) {
int num = 1;
int sqt = 1;
while (x >= sqt)
{
num ++;
sqt = num * num;
}
return num-1;
}
補充說明(Supplement):
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.127.200.146
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1544772949.A.B14.html
推
12/14 15:47,
5年前
, 1F
12/14 15:47, 1F
謝謝前輩 確實是我疏忽了 改成unsigned int 就正常了
不過改成long long還是錯誤 不曉得是什麼原因
※ 編輯: asdfg1597860 (59.127.200.146), 12/14/2018 16:11:22
※ 編輯: asdfg1597860 (59.127.200.146), 12/14/2018 16:16:03
推
12/14 16:29,
5年前
, 2F
12/14 16:29, 2F
確實沒有 這是因為型別不一致的關係嗎 在 sqt = (long long) num*num 確實會變正常
※ 編輯: asdfg1597860 (59.127.200.146), 12/14/2018 16:52:57
推
12/14 19:15,
5年前
, 3F
12/14 19:15, 3F
→
12/14 19:16,
5年前
, 4F
12/14 19:16, 4F
→
12/14 19:16,
5年前
, 5F
12/14 19:16, 5F
謝謝前輩說明
※ 編輯: asdfg1597860 (59.127.200.146), 12/22/2018 15:09:41