Elf
Elf

Reputation: 1

Confused on float and integers, how to make the output exactly as it is, not round up or unnecessary ".0"

I'm trying to make a code to find the gradient of a straight line for my assignment.

It went well but unfortunately it didn't pass 3 test case because the output has decimals so it rounds up the decimals to make it a whole number. This the code;

Ax, Ay = input ().split()
Bx, By = input ().split()
Ax=int (Ax)
Ay=int (Ay)
Bx=int (Bx)
By=int (By)
M=(By-Ay)//(Bx-Ax)
print (M)

input(stdln) -10, 7, 2, 4,

your output

-2

expected output -1.75

but when I make it a float it'll add unnecessary ".0" to whole numbers which will fail test case

Ax, Ay = input ().split()
Bx, By = input ().split()
Ax=float (Ax)
Ay=float (Ay)
Bx=float (Bx)
By=float (By)
M=(By-Ay)/(Bx-Ax)
print (M)

input(stdln) -4, 0, 0, 20,

your output 5.0

expected output 5

Upvotes: 0

Views: 68

Answers (2)

Rabinzel
Rabinzel

Reputation: 7903

you could do a little check before printing. if the result is equal to the integer of result, then it is an integer, else float.

Ax, Ay = input().split()
Bx, By = input().split()
Ax = float(Ax)
Ay = float(Ay)
Bx = float(Bx)
By = float(By)
M = (By-Ay)/(Bx-Ax)

M = int(M) if M==int(M) else float(M)
print(M)

Upvotes: 1

Ifeoluwa
Ifeoluwa

Reputation: 26

When you make arithmetic operations on a float in python, your result will also be a float type. If you want to remove the decimals on your result and make it an integer, simply use the int() function.

M=int((By-Ay)/(Bx-Ax))

This converts your result to an integer type and gets rid of the decimals.

Upvotes: 0

Related Questions