一、Python水仙花數100~999
for i in range(100, 1000):
num_list = list(str(i))
a = int(num_list[0])
b = int(num_list[1])
c = int(num_list[2])
if a**3 + b**3 + c**3 == i:
print(i)
對於100~999的範圍,我們可以使用for循環從100到999進行遍歷,將每個數的各位數值分離出來,按照水仙花數的判定條件進行判斷,如果成立則輸出該數。
二、Python水仙花數的編程代碼
Python水仙花數的代碼可以使用for循環和while循環來實現。
# for循環實現
for i in range(100, 1000):
num_list = list(str(i))
a = int(num_list[0])
b = int(num_list[1])
c = int(num_list[2])
if a**3 + b**3 + c**3 == i:
print(i)
# while循環實現
i = 100
while i <= 999:
num_list = list(str(i))
a = int(num_list[0])
b = int(num_list[1])
c = int(num_list[2])
if a**3 + b**3 + c**3 == i:
print(i)
i += 1
三、Python水仙花數的編程代碼三位數
如果只需要求出三位數的Python水仙花數,則可以使用range(100, 1000)代替range(1, 10)。
for i in range(100, 1000):
num_list = list(str(i))
a = int(num_list[0])
b = int(num_list[1])
c = int(num_list[2])
if a**3 + b**3 + c**3 == i:
print(i)
四、Python水仙花數怎麼找
Python水仙花數是指一個三位數的各位數字的立方和等於該數本身,因此,我們可以將每個三位數按照水仙花數的判定條件進行判斷,如果成立則為水仙花數。
五、Python水仙花數求和
sum = 0
for i in range(100, 1000):
num_list = list(str(i))
a = int(num_list[0])
b = int(num_list[1])
c = int(num_list[2])
if a**3 + b**3 + c**3 == i:
sum += i
print(sum)
對每個符合水仙花數條件的數進行累加求和,最後輸出結果。
六、Python水仙花數for循環
使用for循環來實現Python水仙花數的求解。
for i in range(100, 1000):
num_list = list(str(i))
a = int(num_list[0])
b = int(num_list[1])
c = int(num_list[2])
if a**3 + b**3 + c**3 == i:
print(i)
七、Python水仙花數函數
def narcissistic_number(start, end):
res = []
for i in range(start, end + 1):
num_list = list(str(i))
a = int(num_list[0])
b = int(num_list[1])
c = int(num_list[2])
if a**3 + b**3 + c**3 == i:
res.append(i)
return res
將Python水仙花數封裝成一個函數,可以根據輸入的起始數和終止數來獲取指定範圍內的水仙花數。
八、Python水仙花數的代碼
完整的Python水仙花數代碼如下:
for i in range(100, 1000):
num_list = list(str(i))
a = int(num_list[0])
b = int(num_list[1])
c = int(num_list[2])
if a**3 + b**3 + c**3 == i:
print(i)
九、Python水仙花數1000以內
for i in range(100, 1000):
num_list = list(str(i))
a = int(num_list[0])
b = int(num_list[1])
c = int(num_list[2])
if a**3 + b**3 + c**3 == i and i < 1000:
print(i)
當判斷的範圍為1000以內時,可以在判斷水仙花數的條件中添加i < 1000這個判斷條件。
十、Python水仙花數的編程講解
Python水仙花數指的是一個三位數的各位數字的立方和等於該數本身,例如153是一個水仙花數,因為1的立方加5的立方加3的立方等於153。那麼在Python中如何來判斷一個三位數是否為水仙花數呢?
第一步,使用for循環遍歷100~999的每個數,並將百位、十位、個位數字分離出來。
for i in range(100, 1000):
num_list = list(str(i))
a = int(num_list[0])
b = int(num_list[1])
c = int(num_list[2])
第二步,按照水仙花數的判定條件進行判斷,並輸出符合條件的水仙花數。
if a**3 + b**3 + c**3 == i:
print(i)
通過上述兩個步驟,我們就可以求解出Python水仙花數。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/310133.html