2016-09-27 31 views
1

我需要一些幫助。 我試圖讓我的循環工作與小數,但我的代碼不會接受浮動,我不知道下一步該怎麼做。任何人都可以指出我出錯的地方嗎?你可以在這個循環中使用浮點數嗎?

這是一個代碼,用於將用戶定義的步長(Delta)轉換成攝氏溫度到華氏溫度。那就是:

def main(): 

    # Handshake 
    print("This program will convert a range of Celsius degrees to") 
    print("Fahrenheit degrees based on your input.") 

    # Ask and read low end of range 
    Rangelow = eval(input("Enter the low end of your range: ")) 

    # Ask and read top end of range 
    Rangehigh = 1 + eval(input("Enter the high end of your range: ")) 

    # Ask and read Delta 
    Delta = eval(input("Enter the Delta for your range: ")) 

    #Display output 
    print("Celsius to Fahrenheit by", Delta) 
    for i in range(Rangelow, Rangehigh, Delta): 
     print(i, "    ", 9/5 * i + 32) 



main() 

這是我的意思的例子:

這一計劃將一系列攝氏度轉換爲根據您的輸入 華氏度。 輸入範圍的低端:3.8 輸入範圍的高端:14.7 輸入三角洲爲您範圍:1.1 攝氏度到華氏1.1 回溯(最近通話最後一個): 文件「C:\用戶\ jarre \ Desktop \ Python程序\ Conversion.py「,第27行,在 main() 文件」C:\ Users \ jarre \ Desktop \ Python Programs \ Conversion.py「,第22行,主要爲 範圍內(Rangelow,Rangehigh + 1,Delta): TypeError:'float'對象不能被解釋爲整數

我應該注意到問題似乎在於輸入,輸出沒有問題拋出十進制後輸入已被轉換。

+1

當你說「我的代碼不會接受浮動」,這是什麼意思?如果有回溯,請編輯您的問題並添加它。 – Gerrat

+0

查看文檔:https://docs.python.org/2/library/functions.html ...參數必須是純整數。# – blacksite

+1

附註:請勿在用戶上使用'eval'提供的輸入。如果你期望'float',那麼使用'float'而不是'eval'。如果你想允許'int'或'float'(或任何Python文字),你可以使用['ast.literal_eval'](https://docs.python.org/3/library/ast.html#ast。 literal_eval),它可以安全地處理任意的Python字面值,而無需打開執行任意代碼。 – ShadowRanger

回答

2

不能使用內置的做浮點/小數增量,但它是很容易構建自己的發電機:

def decimal_range(start, stop, increment): 
    while start < stop: # and not math.isclose(start, stop): Py>3.5 
     yield start 
     start += increment 

for i in decimal_range(Rangelow, Rangehigh, Delta): 
    ... 

或者你可以使用numpy但這種感覺就像一把大錘開裂螺母:

import numpy as np 
for i in np.arange(Rangelow, Rangehigh, Delta): 
    ... 
+0

注意:如果您在很多情況下將它與「float」一起使用,則這不會像您所期望的那樣。例如,如果參數爲「0.2,0.3,0.1」,則會得到一個輸出(正確排除「大致爲0.3」的輸出)。但是如果你通過'0.7,0.8,0.1',你會得到兩個輸出,'0.7'和'0.7999999999999 ...'。顧名思義,唯一安全的方法就是直接將輸入字符串轉換爲decimal.Decimal而不是float。 – ShadowRanger

+0

是的,浮動舍入錯誤是一個問題 - 所以同意小數是要走的路。你可以使用'math.isclose()'修復一些Py> 3.5的錯誤 – AChampion

+0

我該如何實現這個?我很難解決這個問題 – Jarbcd

相關問題