实施一个打印给定月份和年份日历的功能。首先,提示用户:
Enter the month and year:
一旦用户输入有效输入(由空格分隔的两个整数),就会以与UNIX cal
命令的输出类似的格式打印日历。例如,如果用户输入03 2014
,则输出应为:
我需要帮助才能向用户询问此问题所要求的具体输入。我也无法创建能够根据输入打印不同月份的代码,因为每个月都会在不同的一天开始。我不能使用任何太复杂的东西,因为我在编程中学习初学者课程。
到目前为止我只编写了3月份的代码:
#include <stdio.h>
int main()
{
int k, rmd;
printf(" March 2014\n");
printf(" Su Mo Tu We Th Fr Sa\n");
for(k = 1; k < 32; ++k) {
if(k == 1){
printf(" %2d\n", k);
}
else if(k % 7 == 1) {
printf(" %2d\n", k);
}
else {
printf(" %2d", k);
}
}
return 0;
}
答案 0 :(得分:0)
#include <stdio.h>
int isLeapYear( int year ); /* True if leap year */
int leapYears( int year ); /* The number of leap year */
int todayOf( int y, int m, int d); /* The number of days since the beginning of the year */
long days( int y, int m, int d); /* Total number of days */
void calendar(int y, int m); /* display calendar at m y */
int main(void){
int year,month;
printf("Enter the month and year: ");
scanf("%d %d", &month, &year);
calendar(year, month);
return 0;
}
int isLeapYear( int y ) /* True if leap year */
{
return(y % 400 == 0) || ((y % 4 == 0) && (y % 100 != 0));
}
int leapYears( int y ) /* The number of leap year */
{
return y/4 - y/100 + y/400;
}
int todayOf( int y, int m, int d) /* The number of days since the beginning of the year */
{
static int DayOfMonth[] =
{ -1/*dummy*/,0,31,59,90,120,151,181,212,243,273,304,334};
return DayOfMonth[m] + d + ((m>2 && isLeapYear(y))? 1 : 0);
}
long days( int y, int m, int d) /* Total number of days */
{
int lastYear;
lastYear = y - 1;
return 365L * lastYear + leapYears(lastYear) + todayOf(y,m,d);
}
void calendar(int y, int m) /* display calendar at m y */
{
const char *NameOfMonth[] = { NULL/*dummp*/,
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
char Week[] = "Su Mo Tu We Th Fr Sa";
int DayOfMonth[] =
{ -1/*dummy*/,31,28,31,30,31,30,31,31,30,31,30,31 };
int weekOfTopDay;
int i,day;
weekOfTopDay = days(y, m, 1) % 7;
if(isLeapYear(y))
DayOfMonth[2] = 29;
printf("\n %s %d\n%s\n", NameOfMonth[m], y, Week);
for(i=0;i<weekOfTopDay;i++)
printf(" ");
for(i=weekOfTopDay,day=1;day <= DayOfMonth[m];i++,day++){
printf("%2d ",day);
if(i % 7 == 6)
printf("\n");
}
printf("\n");
}