简体   繁体   中英

How do I add two variables together that have decimal values?

I'm new to python and have created a Binary addition program that adds 2 binary numbers together and when I have converted the 2 numbers I have stored the decimal value into the variable Decimal and Decimal2. How do I add these together??

I've tried:

sum = decimal+decimal2
print(sum)

add = sum(decimal+decimal2)
print(add)

These don't cause any errors but give me completely random answers... eg. 1010 (10) + 1111 (15) = 14.. Thanks

To add two binary numbers, you can try something like this:

decimal1 = bin(10)
decimal2 = bin(15)
print(int(decimal1,2)+int(decimal2,2))

It sounds like you're trying to add two numbers together. Here is some code that should do that:

Python 3 version

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(num1 + num2)

Python 2 version

num1 = int(raw_input("Enter first number: "))
num2 = int(raw_input("Enter second number: "))
print(num1 + num2)

Hope this helps :)

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