我想编写一个C程序,通过输入注册日期计算汽车的年数。我只能使用一个int而不是日,月和年作为整数。如果整个日期是int,我怎么能只计算年份?
这是我的代码:
#include <stdio.h>
int main() {
int inputDateOfFirstUse, ageCalculation, age;
printf("\nProgram to calculate the age of a car");
printf("\nPlease enter the date of the first use (in this syntax tt.mm.jjjj): ");
scanf("%i", &inputDateOfFirstUse);
ageCalculation = inputDateOfFirstUse - 2018;
age = ageCalculation;
printf("\nThe car is %i years old.", age);
return 0;
}
答案 0 :(得分:3)
在scanf
中,您可以使用%*i
语法跳过您不关心的值。
#include <stdio.h>
int main() {
int inputDateOfFirstUse, ageCalculation, age;
printf("\nProgram to calculate the age of a car");
printf("\nPlease enter the date of the first use (in this syntax tt.mm.jjjj): ");
scanf("%*i.%*i.%i", &inputDateOfFirstUse); // Skips day and month, reads only year
ageCalculation = 2018 - inputDateOfFirstUse;
age = ageCalculation;
printf("\nThe car is %i years old.", age);
return 0;
}