我想编写一个 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;
}
最佳答案
在 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;
}
关于c - C语言中日期只能输入一个整数,不能输入年月日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48239052/