gpt4 book ai didi

c - 在C中打印带有月份和年份的日历

转载 作者:太空宇宙 更新时间:2023-11-04 03:44:09 24 4
gpt4 key购买 nike

我正在尝试制作一个程序,打印出用户输入的给定年份和月份中的月份。到目前为止,我所拥有的只是打印出整个日历年。

#include<stdio.h>

int determineleapyear(int year);
int days_in_month[]= {0,31,28,31,30,31,30,31,31,30,31,30,31};
char *months[]=
{
" ",
"\n\n\nJanuary",
"\n\n\nFebruary",
"\n\n\nMarch",
"\n\n\nApril",
"\n\n\nMay",
"\n\n\nJune",
"\n\n\nJuly",
"\n\n\nAugust",
"\n\n\nSeptember",
"\n\n\nOctober",
"\n\n\nNovember",
"\n\n\nDecember"
};

int determinedaycode(int year)
{
int d1, d2, d3;
d1 = year/4.0;
d2 = year/100.;
d3 = year/400.;
return 1 + (year + d1 + d2 + d3 + 1) % 7;
}

int determineleapyear(int year)
{
return (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0));
}

void calendar(int year, int month, int daycode)
{
int day;
printf("%s", months[month]);
printf("\n\nSun Mon Tue Wed Thu Fri Sat\n");

//Correct the position for the first date
for (day = 1; day <= 1 + daycode * 5; day++)
{
printf(" ");
}

//Print all the dates for one month
for (day = 1; day <= days_in_month[month]; day++)
{
printf("%2d", day);

//Is day before Sat? Else start next line Sun.
if ((day + daycode) % 7 > 0)
printf(" ");
else
printf("\n ");
}
// Set position for next month
daycode = (daycode + days_in_month[month]) % 7;

if (determineleapyear(year))
days_in_month[2] = 29;
printf("\n %s %d\n", months[month], year);
}

//------------------------------------------
int main() {
int daycode, month, year;

printf("\nEnter the month: ");
scanf("%d", &month);
if (month < 1 || month > 12)
{
printf("Error: month must be in range 1..12");
return printf("\nEnter the month: ");
scanf("%d", &month);
}

printf("\nEnter the year: ");
scanf("%d", &year);
if (year < 0)
{
printf("Error: year must be > 0");
return scanf("%d", &year);
}

daycode = determinedaycode(year);
calendar(year, month, daycode);
printf("\n");

return 0;
}

任何人都可以帮我让它打印一个月吗?

最佳答案

您的 calendar 函数正在运行从 1 到 12 的循环,这导致打印所有月份。删除循环并将其替换为允许用户选择月份的参数:

void calendar(int year, int month, int daycode)
{
int day;

printf("%s", months[month]);
printf("\n\nSun Mon Tue Wed Thu Fri Sat\n");

//Correct the position for the first date
for (day = 1; day <= 1 + daycode * 5; day++)
{
printf(" ");
}

//Print all the dates for one month
for (day = 1; day <= days_in_month[month]; day++)
{
printf("%2d", day);

//Is day before Sat? Else start next line Sun.
if ((day + daycode) % 7 > 0)
printf(" ");
else
printf("\n ");
}

// Set position for next month
daycode = (daycode + days_in_month[month]) % 7;
}

使用从输入中读取的变量在 main 中调用它:

calendar(year, month, daycode);

我还强烈建议验证输入。类似于以下内容:

printf("\nEnter the month: ");
scanf("%d", &month);
if (month < 1 || month > 12)
{
printf("Invalid month selected");
return -1;
}

关于c - 在C中打印带有月份和年份的日历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26227212/

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