在浮点和整数上混淆,如何使输出完全按原样进行,而不是圆形或不必要的“ .0”。

发布于 2025-01-30 15:16:24 字数 592 浏览 3 评论 0原文

我正在尝试制作一个代码,以找到我的作业的直线梯度。

它进行得很好,但不幸的是,它没有通过3个测试案例,因为输出有小数,因此将小数组合起来以使其成为整个数字。 这是代码;

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)

输入(STDLN) -10,7, 2,4,

您的输出

-2

预期输出 -1.75

但是当我使其成为浮子时,它将不必要的“ .0”将其添加到整个数字中,这将使测试案例

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)

输入失败(stdln) -4、0, 0、20,

您的输出 5.0

预期输出 5

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

素食主义者 2025-02-06 15:16:24

您可以在打印前进行一点检查。如果结果等于结果的整数,则它是整数,否则浮动。

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)

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)
撩动你心 2025-02-06 15:16:24

当您在Python的浮子上进行算术操作时,您的结果也将是浮动类型。
如果要删除结果上的小数并使其成为整数,只需使用int()函数即可。

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

这将您的结果转换为整数类型,并摆脱小数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文