gpt4 book ai didi

用 C 创建日历

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

我知道我的代码很接近,但它不太有效。

它应该包含日历开始的星期几和该月的天数。

我可以寻求帮助来纠正吗?

int main(void)
{
int start_day, days_in_month, i, day_of_week;

printf("Enter start day: ");
scanf("%d", &start_day);

printf("Enter days in month: ");
scanf("%d", &days_in_month);

for (i = 1 ; i < start_day; i++) {
printf(" ");
}

for (i = 1; i <= days_in_month; i++) {
printf("%2d ", i);
if ((i + start_day - 1) % 7 == 0) {
printf("\n");
}
}
return 0;
}

最佳答案

我可以看到一些小问题:

  • 您应该添加#include <stdio.h>
  • 您不应该定义 day_of_week因为你不使用它。
  • 您可能希望避免在每行末尾打印空格。
  • 如果最后一行不完整,您应该在日历后输出额外的换行符。
  • 您应该测试 scanf 的返回值如果没有输入数字则中止,以避免未定义的行为。

这是更正后的版本:

#include <stdio.h>

int main(void) {
int start_day, days_in_month, i;

printf("Enter start day: ");
if (scanf("%d", &start_day) != 1)
return 1;

printf("Enter days in month: ");
if (scanf("%d", &days_in_month) != 1)
return 1;

for (i = 1; i < start_day; i++) {
printf(" ");
}

for (i = 1; i <= days_in_month; i++) {
printf("%2d", i);
if ((i + start_day - 1) % 7 == 0) {
printf("\n");
} else {
printf(" ");
}
}
if ((days_in_month + start_day - 1) % 7 != 0) {
printf("\n");
}
return 0;
}

关于用 C 创建日历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35098355/

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