如何使Python打印1而不是1.0

7

我正在制作一个数学求解程序,它会将整数打印为小数。例如1会被打印为1.0,5会被打印为5.0,我的代码如下:

print("Type in the cooridinates of the two points.")
    print("")
    print("---------------------")
    print("First point:")
    x1 = int(input("X: "))
    y1 = int(input("Y: "))
    print("")
    print("---------------------")
    print("Second point:")
    x2 = int(input("X: "))
    y2 = int(input("Y: "))
    m = (y1-y2) / (x1-x2)
    b = y1 - m * x1
    round(m, 0)
    round(b, 0)
    print("Completed equation:")
    print("")
    if b < 0:
        print("Y = "+ str(m) +"X - "+ str(b) +".")
    elif b > 0:
        print("Y = "+ str(m) +"X + "+ str(b) +".")
    elif b == 0:
        print("Y = "+ str(m) +"X.")
    input("Press enter to continue.")
4个回答

10

由于您正在除以整数,Python将结果表示为float而不是int。要按您想要的格式格式化float,您必须使用字符串格式化:

>>> print('{:g}'.format(3.14))
3.14
>>> print('{:g}'.format(3.0))
3

因此,将它插入到您的代码中:

print("Y = {:g}X - {}.".format(m, b))

1
你可能会想展示'{:g}''{:.0g}'之间的区别,因为我认为后者可能是他实际想要的。(值得指出的是,他已经试图将数字四舍五入到最近的整数,但是没有成功。) - abarnert

4

试试这个:

> x = 10.0
> print int(x)
10
> print x
> 10.0

这真的是你正在寻找的吗?


0

当你这样做时:

m = (y1-y2) / (x1-x2)

你得到的是浮点数(实数的浮点表示),而不是整数。

然后,因为 m 是浮点数,b 也是浮点数。当你在浮点数上调用 str 时,会得到一个小数点。

正确的修复方法取决于你实际想要做什么。

如果你真的只想处理整数,可以使用整数除法:

m = (y1-y2) // (x1-x2)

这意味着,如果说 x1, x2, y1, y2 = 4, 2, 2, 1,你最终会得到 b = 2 (2 - 0 * 4)。我猜这不是你想要的;你实际上想要将那个 4 乘以 1/2,然后再四舍五入。

在这种情况下,你可以在进行四舍五入的同时进行转换:

m = int(round(m, 0))
b = int(round(b, 0))

请注意,您现有的对round的调用实际上没有做任何事情;round(m, 0)不会修改m,它返回一个新值,该值是m的四舍五入版本,您必须将其重新分配给m(或其他地方)。
还有一件事要考虑:您可能确实想要半个单位,而不是“最接近0.5的浮点表示”。
您可能并不真正关心差异——除非您使用的是相当大的整数,否则舍入误差永远不会可见。但是,如果您确实关心,您可能需要考虑使用第三方精确分数模块(例如clnum),或者可能是标准库decimal。这意味着您必须更加明确,因此我不会这样做,除非您认为有必要。但是,如果确实有必要,它看起来会像这样:
m = decimal.Decimal(y1-y2) / (x1-x2)
b = y1 - m * x1
m = int(m.to_integral(rounding=decimal.ROUND_HALF_UP))
b = int(b.to_integral(rounding=decimal.ROUND_HALF_UP))

最后,您始终可以将数字保留为float(或Decimal等),不进行四舍五入或转换,并强制将它们打印为整数:

print("Y = {:.0g}X - {:.0g}.".format(m, b))

0
Just tried this one

n = -0.0
#n = 0.0
#n = +0.0
#n = 5.0
#n = 5
#n = 5.4
#n = -5.0
#n = -5
#n = 5.25

n = (n**2)**0.5

n = '{:g}'.format(n)

if n.find('.') == -1:
    n=int(n)
else:
    n=float(n)

print(n)
print(type(n))


-------------------------------------------------------------------

The same in one line

n = -0.0
n = int('{:g}'.format((n**2)**0.5)) if 
 '{:g}'.format((n**2)**0.5).find('.') == -1 else 
float('{:g}'.format((n**2)**0.5)) 


-------------------------------------------------------------------

Example for a list


numlist = [-0.0, 0.0, +0.0, 5.0, 5, 5.4, +5.0, +5, +5.15,-5.0, -5, 5.25]
print(f'Numbers are {numlist}')

for n in numlist:
    print(f'Before n is {n} and type of n is {type(n)}')
    n = int('{:g}'.format((n**2)**0.5)) if '{:g}'.format((n**2)**0.5).find('.') 
    == -1 else float('{:g}'.format((n**2)**0.5)) 
    print(f'After n is {n} and type of n is {type(n)}')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接