[問題] 簡單的迴圈問題

看板Python作者時間6年前 (2019/06/23 22:35), 編輯推噓4(404)
留言8則, 5人參與, 6年前最新討論串1/3 (看更多)
大家好 題目是假設給一個n 要print出小於n的square number 例如 n給25 則print出 1 4 9 16 我的code會把0也print 提示說就是寫一個while loop 所以我也就是照提示寫 如下: 還請各位高手幫忙 謝謝! import math n=int(input()) counter=0 while counter*counter<n: A=counter*counter if (A<0): continue counter = counter+1 counter+1 <math.sqrt(n) print(A) 我試圖想要讓print只給我大於0的結果 但沒有成功 -- -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 68.180.87.229 (美國) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1561300547.A.253.html

06/23 23:28, 6年前 , 1F
A<0還是包含0啊,而且你何不counter從1開始
06/23 23:28, 1F

06/23 23:31, 6年前 , 2F
A<=0 不就可以了嗎
06/23 23:31, 2F

06/23 23:34, 6年前 , 3F
差點誤導你 還得把counter自加轉到條件語句的上面
06/23 23:34, 3F

06/24 01:03, 6年前 , 4F
那個counter+1<math.sqrt(n)要幹嘛阿
06/24 01:03, 4F

06/24 11:16, 6年前 , 5F
counter從1開始就可以了(終於..)謝謝!! 回樓上 因為
06/24 11:16, 5F

06/24 11:16, 6年前 , 6F
之前我的答案是從1開始 但包含n本身 所以也fail
06/24 11:16, 6F

07/04 22:36, 6年前 , 7F
這邏輯滿亂的 建議你可以用for迴圈重寫 不要用while
07/04 22:36, 7F

07/08 01:31, 6年前 , 8F
我今天又再寫一次 又包含n 所以我又回來看orz
07/08 01:31, 8F
文章代碼(AID): #1T3uv39J (Python)
文章代碼(AID): #1T3uv39J (Python)