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

如何用单个整数存储登记日期计算车龄的C语言技术问询

How to Calculate Car Age from a Single Integer Date (Year-Only Calculation)

Hey there! Let's sort out your car age calculation problem. The main issue with your current code is that you're subtracting 2018 directly from the full date integer—which doesn't work, since that integer includes day, month, and year all rolled into one. Here's how to fix it step by step:

The Core Problem

Your input is an integer representing a date like ttmmyyyy (e.g., 15052010 for 15th May 2010). When you subtract 2018 from this large number, you're not comparing years—you're just doing a meaningless arithmetic operation on the entire date value. We need to first extract the year from that integer, then compare it to the current year.

Solution Code

Here's a revised version of your program that correctly extracts the registration year and calculates the car's age based on the current system year:

#include <stdio.h>
#include <time.h>

int main() {
    int inputDateOfFirstUse, registrationYear, currentYear, age;
    
    printf("\nProgram to calculate the age of a car");
    printf("\nPlease enter the date of the first use (without dots, e.g., 15052010 for 15.05.2010): ");
    scanf("%d", &inputDateOfFirstUse);
    
    // Extract the 4-digit registration year from the input integer
    registrationYear = inputDateOfFirstUse % 10000;
    
    // Get the current year from the system clock
    time_t now = time(NULL);
    struct tm *currentTime = localtime(&now);
    currentYear = currentTime->tm_year + 1900; // tm_year counts years since 1900
    
    // Calculate the car's age
    age = currentYear - registrationYear;
    
    printf("\nThe car is %d years old.", age);
    return 0;
}

Key Explanations

  • Extracting the Year: Since your input integer ends with the 4-digit year, using the modulus operator % 10000 gives us the last four digits (the year). For example, 15052010 % 10000 returns 2010.
  • Getting the Current Year: We use the time.h library to fetch the current system date. The tm_year field stores years since 1900, so adding 1900 converts it to the actual calendar year.
  • Fixed Age Calculation: Now we're subtracting the registration year from the current year—this gives a meaningful age value.

Notes

  • Make sure users input the date without dots (e.g., 01012020 instead of 01.01.2020). If you try to read a dotted date with %d, it will only capture the day part (since the dot acts as a separator).
  • If you don't want to rely on the system clock, you can replace the current year code with a fixed value (like 2024) or add a prompt for the user to enter the current year.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:06:34