我正在做一個科學記數法寫程序,所以讓我給你的代碼:無故障不執行正確
import time
def scientific_notation(number):
decimal = ""
for thing in str(number):
"""
Loops through the number to add stuff to "decimal"
(probably not necessary but i'm going to keep it
there in case I need a filter.)
"""
if len(decimal) == len(str(number)):
break
else:
decimal += thing
decimal = decimal.replace('0','')
print(decimal)
while float(decimal) > 10:
# Uses decimal notation
actual = ''
# To keep track of the original place
for x in range(0,len(str(number))):
actual += str(number)[x]
decimal = decimal.replace(str(number)[x],str(number)[x]+'.')
# Adding decimal points to each place until the float version of that is less than 10
if decimal.count('.') > 1:
# if there's more than one decimal, replace that value with what it was before
decimal = decimal.replace(str(number)[x],actual)
elif float(decimal) > 10:
# if the float version of the decimal is more than 10, wait for the while loop to realize that by doing nothing
pass
else:
pass
else:
# Output
power = '10^'+str(str(number).count('0'))
print(decimal+" * "+power)
scientific_notation(102)
好了,現在你已經看了它讓我告訴你,這是怎麼回事上。
因此,while循環,我的if語句沒有執行
if decimal.count('.') > 1
,或者至少,不執行正確,這是造成一
ValueError: could not convert string to float: '1.102.'
,因爲我while循環試圖轉換它浮動,但得到'1.102'。並引發ValueError,因爲您無法將具有兩個小數點的東西轉換爲浮點數。關於爲什麼if語句不工作的任何想法?我不知道,也許我只是在愚蠢。
堆棧溢出的[片段](https://stackoverflow.blog/2014/09/16/introducing-runnable-javascript-css-and-html-code-snippets/)是目前僅針對網絡相關(HTML/CSS/JS)的問題。如果你輸入python代碼,他們什麼都不做。 – stybl
@stybl對不起,我該如何格式化Python代碼? –
查看[this](https://stackoverflow.com/editing-help)幫助中心頁面,其中解釋瞭如何在SO上進行格式化。如果您尚未閱讀,請參閱[https://stackoverflow.com/tour],然後閱讀[如何提問](https://stackoverflow.com/help/how-詢問)瞭解如何提出一個好問題的信息。 – stybl