gpt4 book ai didi

C、打印用户选择的月份

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

我正在做一个学校项目,我需要要求像日历一样打印一年和一个月。问题是,当我调试时,它显示全年,而不仅仅是所选的月份。我必须做哪些改变?希望你能帮我!这是我的代码:

int SetFirstDay(int year)
{
int d;
int d1, d2, d3;

d1 = (year - 1.) / 4.0;
d2 = (year - 1.) / 100.;
d3 = (year - 1.) / 400.;
d = (year + d1 - d2 + d3) % 7;
return d;
}

int main()
{
int day, month, year, ndays, DayWeek = 0, FirstDay;
do
{
printf("\nEnter the desired year [2000 - 2099]\n");
scanf_s(" %d", &year);
} while (year < 2000 || year > 2100);

do
{
printf("\nEnter the desired month [1 - 12]\n");
scanf_s(" %d", &month);
} while (month < 1 || month > 12);


char *months[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
int DayMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
DayMonth[1] = 29;

FirstDay = SetFirstDay(year);

for (month = 0; month < 12; month++)
{
ndays = DayMonth[month];
printf("\n\n--------------%s-----------------\n", months[month]);
printf("\n Sun Mon Tue Wed Thu Fri Sat\n");

for (DayWeek = 0; DayWeek < FirstDay; DayWeek++)
{
printf(" ");
}

for (day = 1; day <= ndays; day++)
{
printf("%5d", day);

if (++DayWeek > 6)
{
printf("\n");
DayWeek = 0;
}
FirstDay = DayWeek;
}
}
printf("\n\n\n");
system("pause");
return 0;
}

最佳答案

将用户输入的月份值保存到附加变量中:

int monthTmp = month;

然后在所有 printf 调用前面加上以下带有“月”for 循环的语句:

for (month = 0; month < 12; month++)   
{
// ...
if (monthTmp==month) printf(.........

这不是一个优化的解决方案,但非常简单。

关于C、打印用户选择的月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58902274/

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