使用Python嵌套循环计算双倍余额递减折旧时计算错误求助
双倍余额递减折旧计算代码修正
原代码在计算双倍余额递减折旧时存在多处逻辑和格式错误,导致输出不符合预期,以下是问题分析和修正方案:
原代码问题点
- 金额未格式化:缺少千分位分隔、未保留两位小数,不符合示例输出格式
- 年初价值逻辑颠倒:循环内先扣除折旧再输出年初价值,导致数值错误
- 累计折旧输出错误:循环中误将当年折旧额当作累计折旧输出
- 最后一年折旧未处理:未按规则将剩余账面价值全额计提折旧
修正后的代码
import locale # 设置本地化格式,用于金额的千分位和小数处理 locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') desc_of_item = input("Enter the description of the item: ") yr_of_purchase = int(input("Enter the year of purchase: ")) cost = int(input("Enter the cost: $")) estimated_life = int(input("Enter the estimated life (in years): ")) dep_method = int(input("""Enter the value corresponding to the depreciation method you want to use: 1. Straight-Line 2. Double-Declining Balance Here: """)) if dep_method == 1: depreciation = (1 / estimated_life) * cost print(f"The depreciation of {desc_of_item} using the straight-line method is: ${depreciation:.2f}") elif dep_method == 2: # 输出资产基本信息 print(f"""Description: {desc_of_item} Year of purchase: {yr_of_purchase} Cost: {locale.currency(cost, grouping=True)} Estimated life of item (years): {estimated_life} Method of depreciation: Double-Declining Balance """) current_value = cost total_depreciation = 0 current_year = yr_of_purchase for year in range(estimated_life): # 输出年初价值 print(f"Value at the beginning of {current_year}: {locale.currency(current_value, grouping=True)}") # 计算当年折旧额:最后一年全额计提剩余价值 if year == estimated_life - 1: depreciation = current_value else: depreciation = (2 / estimated_life) * current_value # 更新累计折旧和当前价值 total_depreciation += depreciation current_value -= depreciation # 输出当年折旧和累计折旧 print(f"Amount of depreciation during {current_year}: {locale.currency(depreciation, grouping=True)}") print(f"Total depreciation during {current_year}: {locale.currency(total_depreciation, grouping=True)}") # 年份递增 current_year += 1
修正说明
- 金额格式化:引入
locale模块实现金额的千分位分隔和两位小数显示,与示例输出格式一致 - 逻辑顺序调整:先输出当年年初价值,再计算折旧,避免数值颠倒
- 累计折旧修正:始终输出累计折旧的总和,而非当年折旧额
- 最后一年处理:判断到最后一年时,直接将剩余账面价值作为折旧额,确保最终累计折旧等于资产成本
内容的提问来源于stack exchange,提问作者Mina Milad
相关产品推荐
相关产品推荐

