[英]How to create a program to calculate sums of two numbers?
I'm trying to create a program where you add two decimal numbers eg 552.12 and 25.12 mentally and the program returns correct and wrong based on the input by the user.我正在尝试创建一个程序,您可以在其中添加两个十进制数字,例如 552.12 和 25.12,程序会根据用户的输入返回正确和错误。 I tried inputting the correct answer but it still returns "Wrong".
我尝试输入正确的答案,但它仍然返回“错误”。 Why is it so?
为什么会这样?
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")
This line of code will insert a string into the variable answer:这行代码将在变量 answer 中插入一个字符串:
answer = input("Please enter your answer: ")
So you need to convert answer to float type in order to compare it to result:因此,您需要将答案转换为浮点类型,以便将其与结果进行比较:
if (float(answer) == result):
print("Correct")
else:
print("Wrong")
input()
returns a string. input()
返回一个字符串。 You need to convert it to float
using the float()
function.您需要使用
float()
function 将其转换为float
。 So, change所以,改变
if (answer == result):
to至
if (float(answer) == result):
Hope that this will help you.希望这会对您有所帮助。
First off, the result will be a float and it will have a long decimal place.首先,结果将是一个浮点数,并且会有一个长小数位。 So you have to round that to 2 decimal places.
因此,您必须将其四舍五入到小数点后 2 位。 Once you have done that, you have to convert the float value to a string and compare it to the answer.
完成此操作后,您必须将浮点值转换为字符串并将其与答案进行比较。
Here's the if statement that you need to change to....这是您需要更改为的 if 语句....
if (answer == str(round(result,2))):
print("Correct")
else:
print(result)
print("Wrong")
Output: 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
You need to convert the data stored in your answer
to float.您需要将存储在
answer
中的数据转换为浮点数。 Here's the corrected code:这是更正后的代码:
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")
Moreover, OP already rounded result to 2 decimal places in these lines此外,OP 已经在这些行中将结果四舍五入到小数点后 2 位
cash1 = round(random.uniform(0,1000), 2)
cash2 = round(random.uniform(0,1000), 2)
So no need to round them again所以不需要再次舍入它们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.