如何用单个整数存储登记日期计算车龄的C语言技术问询
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
% 10000gives us the last four digits (the year). For example,15052010 % 10000returns2010. - Getting the Current Year: We use the
time.hlibrary to fetch the current system date. Thetm_yearfield 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.,
01012020instead of01.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

