2017-09-22 74 views
0

我正在做一個科學記數法寫程序,所以讓我給你的代碼:無故障不執行正確

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語句不工作的任何想法?我不知道,也許我只是在愚蠢。

+0

堆棧溢出的[片段](https://stackoverflow.blog/2014/09/16/introducing-runnable-javascript-css-and-html-code-snippets/)是目前僅針對網絡相關(HTML/CSS/JS)的問題。如果你輸入python代碼,他們什麼都不做。 – stybl

+0

@stybl對不起,我該如何格式化Python代碼? –

+0

查看[this](https://stackoverflow.com/editing-help)幫助中心頁面,其中解釋瞭如何在SO上進行格式化。如果您尚未閱讀,請參閱[https://stackoverflow.com/tour],然後閱讀[如何提問](https://stackoverflow.com/help/how-詢問)瞭解如何提出一個好問題的信息。 – stybl

回答

2

Eek你的代碼是可怕的,並做一些意想不到的事情馬上。例如:

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 = str(number) 

decimal = decimal.replace('0','') 

那會使10212不能是故意的。


讓我們看看不同的算法,並用算術而不是字符串處理來處理。

def scientific_notation(number): 
    n = 0 
    while number > 10: 
     n += 1 
     number /= 10 
    print(f"{number} * 10^{n}") 

>>> scientific_notation(102) 
1.02 * 10^2 
+0

是的,我很愚蠢。謝謝! –

+0

另外,我認爲值得注意的是,無論何時你開始爲範圍(len(some_variable))寫入':some_variable [i]',你幾乎肯定會做錯。 Python有一個'enumerate'內建函數,非常高興地讓你迭代元素,同時跟蹤索引。對於我來說,枚舉(some_variable)是更受歡迎的。 –

+0

這個習語對我來說變得如此平常,以至於當我所關心的只是索引時,我有幾次發現自己在寫'爲我,在列舉(某物)「。 –