打印带字符串的整数时出错

2024-04-26 09:53:55 发布

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

我是python的初学者,试图写这个,但是没有用。有什么帮助吗?你知道吗

CP=input("enter the cost price: ")
SP=input("enter the sale price: ")
if (SP>CP):
    print ("Congratulations !! you made a profit of ", + SP-CP) 
    print("Congratulations!! you made a profit of %f" % SP-CP)
elif (CP>SP):
    print("you are in loss of %f" % CP-SP)
else:
    print("you got nothing")

Tags: oftheyouinputsalecppricesp
1条回答
网友
1楼 · 发布于 2024-04-26 09:53:55

在python3中(我假设您正在使用它是因为包含了python-3.x标记),input函数返回一个字符串,您不能对字符串进行数学运算。你需要改变

CP=input("enter the cost price: ")
SP=input("enter the sale price: ")

CP = int( input("enter the cost price: ") )
SP = int( input("enter the sale price: ") )

(添加空格以显示我所更改的内容)。你知道吗

如上所述,您还需要在替换值周围添加括号,以便

print("Congratulations!! you made a profit of %f" % SP-CP)

变成

print("Congratulations!! you made a profit of %f" % (SP-CP) )

(编辑:本杰明以3秒的优势击败我!)你知道吗

网友
2楼 · 发布于 2024-04-26 09:53:55

内置输入返回一个字符串。你需要把它扔到下面的浮子上。当然,假设一个浮点数是你想要的。可以使用int()对整数执行相同的操作。你知道吗

CP=float(input("enter the cost price: "))
SP=float(input("enter the sale price: "))
if (SP>CP): 
    print("Congratulations!! you made a profit of %f" % (SP-CP))
elif (CP>SP):
    print("you are in loss of %f" % (CP-SP))
else:
    print("you got nothing")
网友
3楼 · 发布于 2024-04-26 09:53:55

简短回答

你需要在SP-CPCP-SP之间加上括号。你知道吗

解释

字符串格式运算符%首先计算,不能从字符串中减去数字。你知道吗

就像你在写作一样

print(("Congratulations!! you made a profit of %f" % SP)-CP)

但你想要的是

print("Congratulations!! you made a profit of %f" % (SP-CP))

进一步阅读

您可以找到运算符优先级(首先计算哪个运算符)here。请参阅脚注8:字符串格式运算符%与模运算符%具有相同的优先级。你知道吗

相关问题 更多 >