累加税计算

2024-10-05 14:27:56 发布

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

我在尝试创建一个计算器来计算税收。我已经有意见询问他们是否单身、已婚等,以及他们挣多少钱。我已经计算过他们属于哪一类了。我遇到的问题是累计百分比。你知道,你工资的前9325是10%,后37950是15%等等。。我在试着用

for income in range(0, 9325):

但是如果你把它放进去,比如说9326,它会跳到下一个括号里。不管怎样,这是我当前的代码(嗯,它的主要功能。你可以在https://repl.it/@Sphelix/FlusteredClumsyDemo找到整件事:

if thing == "1" and income <= 9325:
 print("Your tax rate is 10%")
elif thing == "1" and income <= 37950:
 print("Your tax rate is 15%")
elif thing == "1" and income <= 191650:
 print("Your income is 28%")
elif thing == "1" and income <= 416700:
 print("Your tax rate is 33%")
elif thing == "1" and income <= 418000:
 print("Your tax rate is 35%")
elif thing == "1" and income >= 418001:
 print("Your tax rate is 39.6%")

Tags: andforyourrateis计算器税收意见
1条回答
网友
1楼 · 发布于 2024-10-05 14:27:56

For循环通常不用于检查范围。比较运算符(<, >, <=, >=)用于此类型的任务。在您的例子中,收入是浮动的,因此如果您想使用for循环检查所有可能的收入,那么必须执行9325 * 2**64检查。但如果你想成功,你可以做到

import struct

def reinterpretAsInt(f):
    return struct.unpack('Q', struct.pack('d', f))[0]

def reinterpretAsFloat(n):
    return struct.unpack('d',struct.pack('Q', n))[0]

for testIncome in range(0,reinterpretAsInt(9325)):
    # print('Checking income amount: ' + str(reinterpretAsFloat(testIncome)))
    if income == reinterpretAsFloat(testIncome):
        print("Your tax rate is 10%")
        break

如果运行此代码,您将意识到使用for循环检查每个可能的收入水平是多么低效。对于这类问题,应该使用比较运算符。您当前的代码很好,但是您可以将所有thing == "1"检查压缩为一个if语句。你知道吗

相关问题 更多 >