NextDate问题:输入三个变量month、day和year,输出:输入日期后一天的日期,年份区间为1-2050年。用C语言和J编写以上程序
时间: 2024-10-24 18:09:30 浏览: 20
在C语言中,你可以通过库函数`mktime()`和`localtime()`处理日期运算,但由于它们不是严格的类型安全,下面是一个示例,它假设用户提供的月份、天数和年份在有效范围内:
```c
#include <stdio.h>
#include <time.h>
void next_date(int month, int day, int year) {
time_t now = mktime(&tm_year{year - 1900}, // mktime需要从公元1900年开始计数
&tm_mon{month - 1}, // January is 0
day, // day of month
0, // hour (default)
0, // minute (default)
0, // second (default)
0, // weekday (default)
0, // julian day (default)
-1); // timezone (UTC)
struct tm* result = localtime(&now);
if (result == NULL) {
printf("Invalid date!\n");
return;
}
printf("Next Date: %d-%02d-%d\n", result->tm_year + 1900, result->tm_mon + 1, result->tm_mday);
}
int main() {
int month, day, year;
printf("Enter month (1-12), day (1-31), and year (1901-2050): ");
scanf("%d %d %d", &month, &day, &year);
// 检查年份是否在有效范围
if (year < 1901 || year > 2050) {
printf("Year out of range!\n");
return 1;
}
next_date(month, day, year);
return 0;
}
```
对于Java,可以使用`java.time.LocalDate`类更方便地处理日期,这里同样需要校验年份范围:
```java
import java.time.LocalDate;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter month (1-12), day (1-31), and year (1901-2050): ");
int month = scanner.nextInt();
int day = scanner.nextInt();
int year = scanner.nextInt();
// Check year range
if (year < 1901 || year > 2050) {
System.out.println("Year out of range!");
return;
}
// Add one day to the given date
LocalDate inputDate = LocalDate.of(year, month, day);
LocalDate nextDate = inputDate.plusDays(1);
System.out.printf("Next Date: %d-%02d-%d%n", nextDate.getYear(), nextDate.getMonthValue(), nextDate.getDayOfMonth());
}
}
```
阅读全文