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
CodePudding user response:
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)
CodePudding user response:
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.