You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python二手车价值计算器开发求助(附错误实现代码)

二手车价值计算器正确实现方案

任务要求

根据新车价格和车龄,按以下折旧规则计算挪威克朗(NOK)计价的贬值额和剩余价值:

  • 第1年:贬值新车价格的20%
  • 第2年:贬值第1年后剩余价值的14%
  • 第3年:贬值第2年后剩余价值的13%
  • 第4年:贬值第3年后剩余价值的12%
  • 第5年:贬值第4年后剩余价值的11%
  • 第6年及以后:每年贬值上一年剩余价值的10%

程序需满足:

  • 输出购买价、车龄、贬值额、剩余价值
  • 支持用户多次运行计算

错误代码分析

你提供的代码完全偏离任务需求,错误地使用pandas等库处理CSV数据集,未实现任何计算器逻辑:

# importing section
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy as sp

# using the Csv file
df = pd.read_csv('output.csv')

# Checking the first 5 entries of dataset
df.head()

headers = ["symboling", "normalized-losses", "make",
           "fuel-type", "aspiration", "num-of-doors",
           "body-style", "drive-wheels", "engine-location",
           "wheel-base", "length", "width", "height", "curb-weight",
           "engine-type", "num-of-cylinders", "engine-size",
           "fuel-system", "bore", "stroke", "compression-ratio",
           "horsepower", "peak-rpm", "city-mpg", "highway-mpg", "price"]

df.columns = headers
df.head()

data = df

# Finding the missing values
data.isna().any()

# Finding if missing values
data.isnull().any()

# converting mpg to L / 100km
data['city-mpg'] = 235 / df['city-mpg']
data.rename(columns={'city_mpg': "city-L / 100km"}, inplace=True)

print(data.columns)

# checking the data type of each column
data.dtypes 

正确实现代码

以下是符合需求的Python实现,通过循环和条件判断处理折旧逻辑,支持多次运行:

def calculate_car_value():
    # 获取用户输入并做合法性验证
    while True:
        try:
            purchase_price = float(input("请输入新车价格(NOK):"))
            if purchase_price <= 0:
                print("价格必须大于0,请重新输入!")
                continue
            age = int(input("请输入车龄(年):"))
            if age < 0:
                print("车龄不能为负数,请重新输入!")
                continue
            break
        except ValueError:
            print("输入无效,请输入数字!")

    remaining_value = purchase_price
    total_depreciation = 0.0

    # 按年计算折旧
    for year in range(1, age + 1):
        if year == 1:
            depreciation = remaining_value * 0.20
        elif year == 2:
            depreciation = remaining_value * 0.14
        elif year == 3:
            depreciation = remaining_value * 0.13
        elif year == 4:
            depreciation = remaining_value * 0.12
        elif year == 5:
            depreciation = remaining_value * 0.11
        else:
            # 第6年及以后统一按10%折旧
            depreciation = remaining_value * 0.10
        
        total_depreciation += depreciation
        remaining_value -= depreciation

    # 格式化输出结果,保留两位小数
    print("\n--- 计算结果 ---")
    print(f"购买价:{purchase_price:.2f} NOK")
    print(f"车龄:{age} 年")
    print(f"总贬值额:{total_depreciation:.2f} NOK")
    print(f"剩余价值:{remaining_value:.2f} NOK")

# 支持多次运行计算
while True:
    calculate_car_value()
    again = input("\n是否继续计算?(y/n):").strip().lower()
    if again != 'y':
        print("程序结束!")
        break

代码说明

  • 输入验证:确保用户输入的价格为正数、车龄为非负整数,自动处理非法输入场景
  • 折旧计算:通过循环逐年迭代,根据对应年份的折旧率计算贬值额,累计总贬值并更新剩余价值
  • 多次运行:外层循环允许用户重复计算,直到主动选择退出
  • 结果格式化:输出结果保留两位小数,符合货币数值的显示规范

内容的提问来源于stack exchange,提问作者ChiefFenix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 01:45:35