gpt4 book ai didi

C 程序 我想知道是否有办法简化我的 dayofyear 程序?

转载 作者:行者123 更新时间:2023-11-30 21:11:25 26 4
gpt4 key购买 nike

我是 C 语言新手,我编写了这个 C 程序,让用户输入一年中的某一天,作为返回,程序将输出月份以及该月的哪一天。该程序运行良好,但我现在想简化该程序。我知道我需要一个循环,但我不知道如何去做。这是程序

#include <stdio.h>

void SplitDate(int dayofyear, int year, int *month, int *day);

int main() {
int month[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int year, dayofyear, *day;

printf("Enter the day of the year: ");
scanf("%d", &dayofyear);
printf("Enter the year: ");
scanf("%d", &year);
printf("Day %d of year %d falls on:\n ",dayofyear, year);

SplitDate(dayofyear, year, month, day);

}

void SplitDate(int dayofyear, int year, int *month, int *day)
{
if(dayofyear >=1 && dayofyear <= 31)
{
printf("month = 1 day = %d\n",dayofyear);
}
else if(dayofyear >=32 && dayofyear <= 59)
{
printf("month = 2 day = %d\n", dayofyear - 31);
}
else if(dayofyear >=60 && dayofyear <=90)
{
printf("month = 3 day = %d\n", dayofyear - 59);
}
else if(dayofyear >=91 && dayofyear <=120)
{
printf("month = 4 day = %d\n", dayofyear - 90);
}
else if(dayofyear >=121 && dayofyear <=151)
{
printf("month = 5 day = %d\n", dayofyear - 120);
}
else if(dayofyear >=151 && dayofyear <=180)
{
printf("month = 6 day = %d\n", dayofyear - 150);
}
else if(dayofyear >=181 && dayofyear <=211)
{
printf("month = 7 day = %d\n", dayofyear - 180);
}
else if(dayofyear >=212 && dayofyear <=242)
{
printf("month = 8 day = %d\n", dayofyear - 211);
}
else if(dayofyear >=243 && dayofyear <=272)
{
printf("month = 9 day = %d\n", dayofyear - 242);
}
else if(dayofyear >=273 && dayofyear <=303)
{
printf("month = 10 day = %d\n", dayofyear -272 );
}
else if(dayofyear >=304 && dayofyear <=333)
{
printf("month = 11 day = %d\n", dayofyear - 303);
}
else if(dayofyear >=334 && dayofyear <=364)
{
printf("month = 12 day = %d\n", dayofyear - 333);
}
}

最佳答案

void SplitDate(int dayofyear, int year, int *month, int *day){
static int months[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
//months[2] : Requires a correction of leap year
int i;
for(i=1;i<=12;++i){
if(dayofyear > months[i]){
dayofyear -= months[i];
} else {
printf("month = %d\t day = %d\n", i, dayofyear);
break;
}
}
}

关于C 程序 我想知道是否有办法简化我的 dayofyear 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23159835/

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