以字符串形式运行的代码需要将其转换为float [duplicate]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

我只需要帮助将用户的输入转换为浮动全部

谢谢

def takenum(x,y):

    print("Your first number is " + x + " your second number is " + y)

    result = (x + y)

    print(result)

x = input("put your first number: " )

y = input("Put your second number: " )

takenum(x, y)
python-3.x
2个回答
0
投票
def takenum(x,y):
    print("Your first number is " + x + " your second number is " + y)
    result = (float(x) + float(y))
    print(result)

x = input("put your first number: " )
y = input("Put your second number: " )

takenum(x, y)

enter image description here

注意:您的输入应为3.5而不是3,6

使用点作为小数分隔符

或者如果你想使用点和逗号或只是逗号作为分隔符,只需删除(逗号)与replace():

def takenum(x,y):
    print("Your first number is " + x + " your second number is " + y)
    result = (float((x).replace(',','.')) + float((y).replace(',','.')))
    print(result)

x = input("put your first number: " )
y = input("Put your second number: " )

takenum(x, y)

代码在做什么:

float((x).replace(',','.')) 

你有x是字符串(输入是返回字符串),替换,(逗号)。 (点),并将字符串转换为浮点数

enter image description here


0
投票

当您使用float(input())读取它时,可以显式地将输出转换为浮点数,然后使用字符串格式打印它。

def takenum(x,y):
    print("Your first number is {} and your second number is {}".format(x, y))
    result = x + y
    print(result)

x = float(input("put your first number: " ))
y = float(input("Put your second number: " ))

takenum(x, y)

您的输出将如下所示:

put your first number: 5.6
Put your second number: 6.5
Your first number is 5.6 and your second number is 6.5
12.1
© www.soinside.com 2019 - 2024. All rights reserved.