繁体   English   中英

如何创建一个程序来计算两个数字的总和?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM