[英]How to create a program to calculate sums of two numbers?
我正在嘗試創建一個程序,您可以在其中添加兩個十進制數字,例如 552.12 和 25.12,程序會根據用戶的輸入返回正確和錯誤。 我嘗試輸入正確的答案,但它仍然返回“錯誤”。 為什么會這樣?
for i in range(20):
cash1 = round(random.uniform(0,1000), 2)
cash2 = round(random.uniform(0,1000), 2)
result = cash1 + cash2
print("What is the sum of", cash1,"and", cash2)
answer = input("Please enter your answer: ")
if (answer == result):
print("Correct")
else:
print("Wrong")
這行代碼將在變量 answer 中插入一個字符串:
answer = input("Please enter your answer: ")
因此,您需要將答案轉換為浮點類型,以便將其與結果進行比較:
if (float(answer) == result):
print("Correct")
else:
print("Wrong")
input()
返回一個字符串。 您需要使用float()
function 將其轉換為float
。 所以,改變
if (answer == result):
至
if (float(answer) == result):
希望這會對您有所幫助。
首先,結果將是一個浮點數,並且會有一個長小數位。 因此,您必須將其四舍五入到小數點后 2 位。 完成此操作后,您必須將浮點值轉換為字符串並將其與答案進行比較。
這是您需要更改為的 if 語句....
if (answer == str(round(result,2))):
print("Correct")
else:
print(result)
print("Wrong")
Output:
What is the sum of 754.14 and 229.81
Please enter your answer: 983.95
Correct
What is the sum of 177.63 and 853.05
Please enter your answer: 1022.77
1030.6799999999998
Wrong
您需要將存儲在answer
中的數據轉換為浮點數。 這是更正后的代碼:
for i in range(20):
cash1 = round(random.uniform(0,1000), 2)
cash2 = round(random.uniform(0,1000), 2)
result = cash1 + cash2
print("What is the sum of", cash1,"and", cash2)
answer = float(input("Please enter your answer: "))
if (answer == result):
print("Correct")
else:
print("Wrong")
此外,OP 已經在這些行中將結果四舍五入到小數點后 2 位
cash1 = round(random.uniform(0,1000), 2)
cash2 = round(random.uniform(0,1000), 2)
所以不需要再次舍入它們
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.