社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何删除以python结尾的浮点数?[副本]

Muratek • 4 年前 • 255 次点击  

这个问题已经有了答案:

这里是一个初学Python编程的学习者。

我正在用python制作一个非常简单的两位数计算器。虽然它运行得很好,但我无法解决以“.0”结尾的浮点数问题。我想删除这个结尾。我试了几次,但都不管用。我需要在代码中添加什么条件?你能看一下下面吗?

    def calculator():
        num1 = float(input('First number: '))
        operator = input('+, -, / or * ? ')
        num2 = float(input('Second Number: '))

        if operator == '+':
            return print(num1, '+', num2, '=', num1 + num2)
        elif operator == '-':
            return print(num1, '-', num2, '=', num1 - num2)
        elif operator == '/':
            return print(num1, '/', num2, '=', num1 / num2)
        elif operator == '*':
            return print(num1, '*', num2, '=', num1 * num2)

calculator()

提前谢谢!

我完全按照@water winter的建议做了,但每当我执行程序并输入数字和运算符时,就会出现以下错误: if result.is_integer(): AttributeError: 'int' object has no attribute 'is_integer'

更新:看起来只有“/”操作符工作得很好。其他3个操作符给出了上述相同的错误。:

新的更新:最后我设法使计算器编程完美!

def calculator():
    num1 = float(input("First number: "))
    operator = input("Choose: +, -, /, or *")
    num2 = float(input("Second number: "))
    num1 = int(num1) if num1.is_integer() else num1
    num2 = int(num2) if num2.is_integer() else num2
    add = (num1 + num2)
    subtract = (num1 - num2)
    divide = (num1 / num2)
    multiply = (num1 * num2)

    if operator == "+" and add % 1 == 0:
        print(num1, "+", num2, "is equal to:", int(add))
    elif operator == "+" and not add % 1 == 0:
        print(num1, "+", num2, "is equal to:", add)
    elif operator == "-" and subtract % 1 == 0:
        print(num1, "-", num2, "is equal to:", int(subtract))
    elif operator == "-" and not subtract % 1 == 0:
        print(num1, "-", num2, "is equal to:", subtract)
    elif operator == "/" and divide % 1 == 0:
        print(num1, "/", num2, "is equal to:", int(divide))
    elif operator == "/" and not divide % 1 == 0:
        print(num1, "/", num2, "is equal to:", divide)
    elif operator == "*" and multiply % 1 == 0:
        print(num1, "*", num2, "is equal to:", int(multiply))
    elif operator == "*" and not multiply % 1 == 0:
        print(num1, "*", num2, "is equal to:", multiply)

calculator()

谢谢你们的帮助和建议。他们帮了很多忙!:)

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38625
 
255 次点击  
文章 [ 1 ]  |  最新文章 4 年前