Python浮点数对字符串

2024-05-14 15:57:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个加密货币交易利润计算器,它要求用户输入他们购买的加密货币的名称、价格和数量。然后,该程序计算出他们需要出售的价格,以便以不同的百分比获得利润。当我运行此代码时,会收到以下错误消息:

line 16, in <module>
    print("sale Price: " + salePrice)
TypeError: must be str, not float

这是我的密码:

fee = 1.002

cryptoName = input("Crypto Name: ")
boughtPrice = float(input("Price When Bought: "))
numBought = float(input("Number bought: "))

feePrice = boughtPrice * fee

print(" ")
print(" ")

print("**********************")
print(".3% Profit: ")
salePrice = feePrice *1.003
print("**********************")
print("sale Price: " + salePrice)
print("----------------------")
newBalance = salePrice * numBought
invested = numBought * feePrice
totalProfit = newBalance - invested
print("Total Profit: " + totalProfit)

我更习惯于Java,我最初是用Java编写这个程序的,我知道在Java中,你可以对字符串执行数学运算,只要一些数值与它们相关,但正如我发现的,Python是不同的。我应该如何编写不同的代码?你知道吗


Tags: 代码程序input货币价格javasalefloat
1条回答
网友
1楼 · 发布于 2024-05-14 15:57:02

你有一些选择。第一个是转换为字符串并连接:

print("sale Price: " + str(salePrice))

但可以说更好的方法是使用.format()

print("sale Price: {}".format(salePrice))

或者,如果使用Python3.6或更高版本,请使用f-string

print(f"sale Price: {salePrice}")

相关问题 更多 >

    热门问题