题目要求:
编辑程序显示单月日历。用户指定该月有多少天,该月初始日为周几。
输出该月日历。
我在原有题目的基础上润色后,设计如下:
#include<stdio.h>
int main()
{
int days,startday,speciday;
//days是指本月有几天,startday是该月开始的日子,speciday是指指定的日子
printf("Enter number of days in month: \n");
scanf("%d",&days);
printf("Enter strating day of the week(1=Sun,7=Sat): \n");
scanf("%d",&startday);
/**
* 一开始想的太复杂了,后来发现可以给周几编号
* 1=Sun,2=Mon,3=Tues,4=Wed,5=Thurs,6=Fri,7=Sat
*/
printf("本月日历表:\n");
//在日历上方显示今天是周几
for (int i = 0; i < 7; i++)
{
switch (i)
{
case 0:
printf("Sun\t");
break;
case 1:
printf("Mon\t");
break;
case 2:
printf("Tues\t");
break;
case 3:
printf("Wed\t");
break;
case 4:
printf("Thurs\t");
break;
case 5:
printf("Fri\t");
break;
case 6:
printf("Sat\n");
break;
default:
break;
}
}
//想对齐,那么让第一行多余的前面用空格塞满
for (int i = 0; i < startday-1; i++)
{
printf(" ");
}
/**
* 以表格形式显示1到这月最后一天,选择制表符:\t
* 因为想让之间留有空格,所以%4d(每个输出占4,且右对齐)
* 每行最后\n换行
* */
for (int i = startday; i < days+startday; i++)
{
speciday = i % 7;
switch (speciday)
{
case 1:
printf("%d\t",i-startday+1);
break;
case 2:
printf("%4d\t",i-startday+1);
break;
case 3:
printf("%4d\t",i-startday+1);
break;
case 4:
printf("%4d\t",i-startday+1);
break;
case 5:
printf("%4d\t",i-startday+1);
break;
case 6:
printf("%4d\t",i-startday+1);
break;
case 0:
printf("%4d\n",i-startday+1);
break;
default:
printf("错误!");
break;
}
}
printf("\n");
return 0;
}
成果:
Enter number of days in month:
31
Enter strating day of the week(1=Sun,7=Sat):
5
本月日历表:
Sun Mon Tues Wed Thurs Fri Sat
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
用了好久才弄出来,
总结一下:
想让几行数据对齐,采用制表符:\t
想让缺数据的一行与另外几行右对齐,在缺少的地方用空格补上
想输出字符串“Sun”等,发现printf("%4d\t",Sun);会报错,报错原因:Sun未定义。想要去定义Sun,发现Sun属于字符串,我用""双引号括起来去定义——char Sun = "Sun";报错,原因是:char只能定义单字符,不可以定义字符串变量,要想定义字符串变量,应该char arr[] = "Sun";但是这样输出时会很麻烦,毕竟不是一个,而是要输出7个。那么我尝试去定义字符串常量,即#define Sun "Sun" //注意,这里也必须应""引起来。但是这样要定义7个,太麻烦了。最后还是选择printf("Sun\t");进行输出。
回顾代码,我发现我写的代码很啰嗦,还是不行,回来需要再次改进!