简体   繁体   中英

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. 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 = 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. You need to convert it to float using the float() function. 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. 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 (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

You need to convert the data stored in your answer to float. 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

cash1 = round(random.uniform(0,1000), 2)  
cash2 = round(random.uniform(0,1000), 2)  

So no need to round them again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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