在Python中将用户提供的数字转换为整数和浮点数

2024-09-28 17:18:44 发布

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

我正在尝试创建一个“零钱返还”程序,该程序接受物品的成本和所给的钱,并以纸币、25美分硬币、10美分硬币等形式返还适当的零钱

我对编程相当陌生,我一直在尝试将其拆分。我查看了StackOverflow,发现方法math.modf(x)是相关的。然而,我很难实现它

你能告诉我为什么changey{}吗

谢谢

import math

def changereturn():

    quarter = 0.25
    dime = 0.1
    nickel = 0.05
    penny = 0.01

    cost = float(raw_input('Please enter the cost of the item in USD: '))
    money = float(raw_input('Please enter the amount of money given in USD: '))

    change = money - cost


    y = math.modf(change) 

    return change
    return y

Tags: ofthe程序inputraw硬币mathfloat
2条回答

函数(def)只能return一次,但python允许您为结果返回元组

此实现可能是您所需要的:

import math

def changereturn():
    quarter = 0.25
    dime = 0.1
    nickel = 0.05
    penny = 0.01

    cost = float(input('Please enter the cost of the item in USD: '))
    money = float(input('Please enter the amount of money given in USD: '))

    change = money - cost

    y = math.modf(change) 

    return change, y

print(changereturn())

第一个问题是您从未运行过changereturn()函数。第二个问题是changereurn()函数中的两行return。发送y的第二个函数将永远不会运行。您可以返回(更改,y)并按以下方式运行程序:

change, y = changereturn()

print change
print y

你需要把它放在最底部,不要缩进。就我个人而言,我不喜欢从一个函数返回多个东西。通常我会建议将其作为元组捕获,然后打印每个部分。你的问题让人觉得有点像是一个理工科一年级学生的作业,所以我不想1)帮你解决它,2)让它变得过于复杂

相关问题 更多 >