Answer the question
In order to leave comments, you need to log in
Why does Python output a floating point number (Float) when formatted as int?
The bottom line is this, I'm making a program that, with an odd number entered by the user, divides it by 2 and rounds it up. I implemented an odd-even check using If...Else, but when the user enters an even number (like 10), that number is displayed as a floating point number. This was not observed with odd numbers. Tell me how to make an even number displayed in int format. This is very important for me, I'm a beginner, so I don't rummage well
import math
n = int(input())
if n % 2 == 0:
n = n/2
print(n)
else:
c = math.ceil(n / 2)
c = int(c)
print(c)
Answer the question
In order to leave comments, you need to log in
n = n/2
In this line, you divide the number by 2. With such an operation, the float type is returned to you. You can wrap it again in int() before printing
And specifically in your case, you can do without math. You can use integer division (// in python) and add 1 if you want to round up. But that's only if you divide by 2.
math.ceil() rounds and returns an integer in your case. You don't need to convert it to int again:
>>> import math
>>> num = math.ceil(5 / 2)
>>> num
3
import math
n = int(input())
if n % 2 == 0:
n = n/2
print(int(n))
else:
c = math.ceil(n / 2)
print(c)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question