不用担心,您的代码是可以修正的。问题在于条件语句的逻辑和字符串拼接的方式。我将帮助您解释并纠正您的代码。
首先,看一下您的代码:
q20_amount = int(input('Enter a number:'))
q20_amount = 91
if q20_amount//20 == 1:
q20_20 = f'{q20_amount//20} twenty'
if q20_amount//20 > 1:
q20_20 = f'{q20_amount//20} twenties'
if q20_amount//20 < 1:
q20_20 = ''
if (q20_amount%20)//10 == 1:
q20_10 = f'{(q20_amount%20)//10} ten'
if (q20_amount%20)//10 > 1:
q20_10 = f'{(q20_amount%20)//10} tens'
if (q20_amount%20)//10 < 1:
q20_10 = ''
if (q20_amount%10)//5 == 1:
q20_5 = f'{(q20_amount%10)//2} five'
if (q20_amount%10)//5 > 1:
q20_5 = f'{(q20_amount%10)//2} fives'
if (q20_amount%10)//5 < 1:
q20_5 = ''
if (q20_amount%5)//2 > 1:
q20_2 = f'{(q20_amount%5)//2} twos'
if (q20_amount%5)//2 == 1:
q20_2 = f'{(q20_amount%5)//2} two'
if (q20_amount%5)//2 < 1:
q20_2 = ''
if q20_amount%2 == 1:
q20_1 = f'{q20_amount%2} one'
if q20_amount%2 > 1:
q20_1 = f'{q20_amount%2} ones'
if q20_amount%2 < 1:
q20_1 = ''
output20 = q20_20+q20_10+q20_5+q20_2+q20_1
print(output20)
问题在于您在计算需要的纸币数量时,有些地方使用了错误的变量和计算方式。同时,在拼接字符串时,也需要注意一些问题。
我将修正您的代码如下:
q20_amount = int(input('Enter a number:'))
# q20_amount = 91 # 这行代码可以注释掉或删除,因为上面已经有输入语句了。
q20_20 = q20_amount // 20
q20_10 = (q20_amount % 20) // 10
q20_5 = (q20_amount % 10) // 5
q20_2 = ((q20_amount % 10) % 5) // 2
q20_1 = ((q20_amount % 10) % 5) % 2
output20 = ""
if q20_20 == 1:
output20 += f'{q20_20} twenty\n'
elif q20_20 > 1:
output20 += f'{q20_20} twenties\n'
if q20_10 == 1:
output20 += f'{q20_10} ten\n'
elif q20_10 > 1:
output20 += f'{q20_10} tens\n'
if q20_5 == 1:
output20 += f'{q20_5} five\n'
elif q20_5 > 1:
output20 += f'{q20_5} fives\n'
if q20_2 == 1:
output20 += f'{q20_2} two\n'
elif q20_2 > 1:
output20 += f'{q20_2} twos\n'
if q20_1 == 1:
output20 += f'{q20_1} one\n'
elif q20_1 > 1:
output20 += f'{q20_1} ones\n'
print(output20.strip())
这样修改后,您应该能得到正确的输出。您可以根据您输入的不同数字进行测试,输出的格式应该是正确的。 |