gpt4 book ai didi

在 C 中创建日期计算器

转载 作者:太空宇宙 更新时间:2023-11-04 00:59:53 25 4
gpt4 key购买 nike

我需要用 C 创建一个基本的日期计算器,让用户以 YYYY-MM-DD 格式输入日期。我有它的基础知识。虽然我不需要,但我想多花点时间考虑闰年。程序运行良好;但是,它不能正确计算闰年。当我输入日期 2016-02-26 时,我应该得到 2016-03-04 的预期结果,但我得到的结果是 2016-03 -03。我认为如果我使用 if else 语句来实现以下使用模数的效果。

if (month == 2 && year % 4) days = 29; 
else days = 28;

这是我的完整代码...

//Does not require <stdlib.h>
#include <stdio.h>

// Set variables
int newDay, newMonth, newYear, daysInMonth, daysRemain;
// Set structure for day month year
struct date {
int day, month, year;
};
// set structure for date
struct date d1;

int main (void) {
//Intro
printf("Date calculation program by Keith A. Russell");
//Asks for user input
printf("\n\nPlease enter the year in four digit format (YYYY) ");
scanf("%i", &d1.year);
printf("\nEnter the month in two digit format (MM) ");
scanf("%i", &d1.month);
printf("\nEnter the day in two digit format (DD) ");
scanf("%i", &d1.day);
//Runs calculations to increase the date by a week
newDay = d1.day + 7;
newMonth = d1.month;
newYear = d1.year;
daysRemain = 0;
//For if the next week is going to be greater than the next month
if (newDay > 28)
checkMonth(); //Runs checkMonth Function
//Prints the dates
printf("\nThe new date is %i-%i-%i: \n", newYear, newMonth, newDay);
}

checkMonth() {
if (d1.month == 1 || 3 || 5 || 7 || 8 || 10 || 12)
daysInMonth = 31; //For months with 31 days
if (d1.month == 2 && d1.year % 4) //Attempt to calculate leap year
daysInMonth = 29;
else {
daysInMonth = 28; //All other years
}
if (d1.month == 4 || 6 || 9 || 11) //For months with 30 days
daysInMonth = 30;
//Sets up to advance the year if approaching the end of year
if (newDay > daysInMonth) {
daysRemain = newDay - daysInMonth;
newDay = daysRemain;
newMonth++;
checkYear();
}
}
//Runs function to advance to the next year
checkYear() {
if (d1.month == 12)
if (daysRemain > 0) {
newYear++;
newMonth = 1;
}
}

如果有更优雅的方法来计算闰年并将其包含在该程序中,我将不胜感激。谢谢。

最佳答案

首先这是错误的

if (d1.month == 1 || 3 || 5 || 7 || 8 || 10 || 12)

它永远是真的。你需要

if (d1.month == 1 || d1.month == 3 || d1.month == 5 ....)

关于在 C 中创建日期计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44503883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com