Python找到美元和岑

2024-09-29 02:18:10 发布

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

假设price是一个整型变量,其值是以美分为单位的价格(以美元计)。写一份声明,将价格的价值以“X美元和Y美分”的形式单独打印在一行上。所以,如果price的值是4321,您的代码将打印“43美元21美分”。如果值是501,它将打印“5美元1美分”。如果值为99,则代码将打印“0美元99美分”。在

我是这样做的:

print (price/100,"dollars and",price%100, "cents")

结果示例:2314

^{pr2}$

如何使结果看起来像:

23 dollars and 14 cents

Tags: and代码声明示例单位价格price形式
3条回答

输入:

x = 4321

print (x/100),'dollars and',int(100*((x/100.00)-(x/100))),'cents'

输出:

^{pr2}$

您可以使用:

price=2314

print (price/100,"dollars and",price%100, "cents")

这将输出:

^{pr2}$

操作是正确的;在python3中+两者都是

print (price//100,"dollars and",price%100, "cents")

以及

^{pr2}$

给出期望的结果。在


下面是一个包含测试策略的直接字符串处理攻击:

#    *    -*    -*    -*    -*    -*    -*    -*
# Desc: Print Dollars and Cents
#    *    -*    -*    -*    -*    -*    -*    -*

def formatPrint(cents):
    centsStr = str(cents)
    d, c = centsStr[:-2], centsStr[-2:]
    if cents > 99:
        print(d + ' dollars and ' + c + ' cents')
    else:
        print('0 dollars and ' + c + ' cents')
    return 


x = [0,7,23,111,4321,54321]

for ndx in range(0, len(x)):
    print (x[ndx], ':')
    formatPrint(x[ndx])

相关问题 更多 >